Real World Haskell
実戦で学ぶ関数型言語プログラミング
(オライリージャパン)
Bryan O'Sullivan (著) John Goerzen (著)
Don Stewart (著)
山下 伸夫 (翻訳) 伊東 勝利 (翻訳)
株式会社タイムインターメディア (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
- The Haskell Platform (インストール方法、モジュール等)
Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の4章(関数プログラミング)、4.6(ループをどのように考えるか)、4.6.9(左畳み込み、遅延性、スペースリーク)、練習問題 6.を解いてみる。
その他参考書籍
- すごいHaskellたのしく学ぼう!(オーム社) Miran Lipovača(著)、田中 英行、村主 崇行(翻訳)
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
練習問題 6.
コード(BBEdit, Emacs)
exercises.hs
{-# OPTIONS -Wall -Werror #-} module Main where myGroupBy :: (Eq a) => (a -> a -> Bool) -> [a] -> [[a]] myGroupBy _ [] = [] myGroupBy f xs = let (x, ys, xxs) = inner f xs in if ys == [] then xxs ++ [[x]] else xxs ++ [ys] inner :: (a -> a -> Bool) -> [a] -> (a, [a], [[a]]) inner _ [] = (undefined, undefined, []) inner f (x:xs) = foldl (\(y, ys, xxs) z -> if f y z then (y, (ys ++ [z]), xxs) else (z, [z], xxs ++ [ys])) (x, [x], []) xs
入出力結果(Terminal, インタプリタghci)
$ ghci GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> :module Data.List Prelude Data.List> :load Sample.hs [1 of 1] Compiling Main ( Sample.hs, interpreted ) Ok, modules loaded: Main. *Main Data.List> groupBy (==) [] [] *Main Data.List> myGroupBy (==) [] [] *Main Data.List> group group groupBy *Main Data.List> groupBy (==) [1,1,2,2,3,4,5] [[1,1],[2,2],[3],[4],[5]] *Main Data.List> myGroupBy (==) [1,1,2,2,3,4,5] [[1,1],[2,2],[3],[4],[5]] *Main Data.List> groupBy (==) [1,2,3,4,5] [[1],[2],[3],[4],[5]] *Main Data.List> myGroupBy (==) [1,2,3,4,5] [[1],[2],[3],[4],[5]] *Main Data.List> groupBy (<) [1,2,3,4,5] [[1,2,3,4,5]] *Main Data.List> myGroupBy (<) [1,2,3,4,5] [[1,2,3,4,5]] *Main Data.List> groupBy (<) [5,4,3,2,1] [[5],[4],[3],[2],[1]] *Main Data.List> myGroupBy (<) [5,4,3,2,1] [[5],[4],[3],[2],[1]] *Main Data.List> groupBy (<) [1,2,3,4,5,1,2,3,4,5] [[1,2,3,4,5],[1,2,3,4,5]] *Main Data.List> myGroupBy (<) [1,2,3,4,5,1,2,3,4,5] [[1,2,3,4,5],[1,2,3,4,5]] *Main Data.List> group group groupBy *Main Data.List> groupBy (<) [5,4,3,2,1,5,4,3,2,1] [[5],[4],[3],[2],[1,5,4,3,2],[1]] *Main Data.List> myGroupBy (<) [5,4,3,2,1,5,4,3,2,1] [[5],[4],[3],[2],[1,5,4,3,2],[1]] *Main Data.List> :quit Leaving GHCi. $
0 コメント:
コメントを投稿