Real World Haskell
実戦で学ぶ関数型言語プログラミング
Bryan O'Sullivan, John Goerzen, Don Stewart(著)
山下 伸夫, 伊東 勝利
株式会社タイムインターメディア(翻訳)
開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Haskell (純粋関数型)
Real World Haskell』(Bryan O'Sullivan、John Goerzen、Don Stewart(著)、山下 伸夫、伊東 勝利、株式会社タイムインターメディア(翻訳)、オライリー・ジャパン、2009年、ISBN978-4-87311-423-3)の3章(型を定義し、関数を単純化する)の3.13(ガード条件節の評価)の練習問題6.を解いてみる。
6.
コード(BBEdit)
Sample.hs
-- file: sample.hs shorter:: Int -> [[a]] -> [[a]] longer:: Int -> [[a]] -> [[a]] sortByLength::[[a]] -> [[a]] shorter n [] = [] shorter n (x:xs) | length x <= n = [x] ++ shorter n xs | otherwise = [] ++ shorter n xs longer n [] = [] longer n (x:xs) | length x > n = [x] ++ longer n xs | otherwise = [] ++ longer n xs sortByLength [] = [] sortByLength (x:xs) = (sortByLength short) ++ [x] ++ (sortByLength long) where short = shorter (length x) xs long = longer (length x) xs
入出力結果(Terminal)
$ ghci GHCi, version 7.4.2: 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> :load Sample.hs [1 of 1] Compiling Main ( Sample.hs, interpreted ) Ok, modules loaded: Main. *Main> sortByLength [] [] *Main> sortByLength [[],[]] [[],[]] *Main> sortByLength [[],[1]] [[],[1]] *Main> sortByLength [[1],[]] [[],[1]] *Main> sortByLength [[1],[],[1]] [[],[1],[1]] *Main> sortByLength [[1,2],[],[1]] [[],[1],[1,2]] *Main> sortByLength [[1,2],[1],[]] [[],[1],[1,2]] *Main> sortByLength [[],[1,2],[1],[]] [[],[],[1],[1,2]] *Main> sortByLength [[1,2,3],[1,2],[1]] [[1],[1,2],[1,2,3]] *Main> sortByLength [[1],[1,2,3],[1,2]] [[1],[1,2],[1,2,3]] *Main> sortByLength [[1,2],[3,4],[4,3],[1,2]] [[1,2],[4,3],[3,4],[1,2]] *Main> sortByLength [[1,2],[],[1],[0,0,0,0,0],[3,4],[4,3],[1,2]] [[],[1],[1,2],[4,3],[3,4],[1,2],[0,0,0,0,0]] *Main> :quit Leaving GHCi. $
0 コメント:
コメントを投稿