ふつける(1) 2.3 - 2.8 リスト
って、いきなりリストっすか!?
早いっすよ・・・。
リストについて
リストはSchemeと同じように、最後に「空リスト」が入ってる。「空リスト」は「くうリスト」と読むらしい。僕は「からリスト」って読んでた。
Haskellのリストは型が揃ってないとダメ。自由度低いのかなぁ・・・。
実験。
Prelude> [1, 2, 3] [1,2,3] Prelude> ["abc", "def", "ghi"] ["abc","def","ghi"] Prelude> [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] ["abc","def","ghi"] Prelude> [[], [1], [2], [1,2]] [[],[1],[2],[1,2]]
型が揃ってれば集合も表せる。大体の事は表現出来そう。
練習問題
要約すると、「wcを作れ」という問題。
僕の答えは、こんなの。
main = do cs <- getContents pl $ lines cs pl $ words cs pl cs pl a = print $ length a
実行してみる。
% runghc wc.hs < usa-states.txt 50 160 1470
本物は、
% wc < usa-states.txt 50 160 1470
表示が縦に並んじゃってるけど、答えは合ってるみたい。イマイチ!
色々欲しい道具が・・・。
追記
ふつけるの後ろの方を見ながら、頑張って修正。
main = do cs <- getContents wc cs wc cs = do pl lines pl words pl (\a -> a) where pl f = print $ length $ f cs
whereとlambdaを覚えた!!
メモ:インデントに意味がある。
追記2
もうちょっと修正。mapを使って、doを消して、wcと同じように横並び表示。
main = do cs <- getContents wc cs wc cs = putStrLn $ unwords $ map (\a -> show $ length a) [lines cs, words cs, map (\a -> [a]) cs]
Haskell楽しくなってきた!!