Skip to content

Instantly share code, notes, and snippets.

@tan-yuki
Last active August 29, 2015 14:22
Show Gist options
  • Save tan-yuki/e6300e8124a52dc643fc to your computer and use it in GitHub Desktop.
Save tan-yuki/e6300e8124a52dc643fc to your computer and use it in GitHub Desktop.
すごいHaskellたのしく学ぼう 5.5 - 5.7

5.5 畳み込み、見込みあり!

foldrで右畳み込み

map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) [] xs
-- acc
-- []
-- [6]
-- [5,6]
-- [4,5,6]

wrongMap' :: (a -> b) -> [a] -> [b]
wrongMap' f xs = foldl (\acc x -> f x : acc) [] xs
-- acc
-- []
-- [4]
-- [5,4]
-- [6,5,4]

main = do
  putStrLn $ show $ map' (+3) [1..3]
  putStrLn $ show $ wrongMap' (+3) [1..3]

cf) accumulator

アキュムレータ(英: Accumulator)は、コンピュータにおいて、演算装置による演算結果を累積する、すなわち総和を得るといったような計算に使うレジスタや変数のことである。

http://ja.wikipedia.org/wiki/%E3%82%A2%E3%82%AD%E3%83%A5%E3%83%A0%E3%83%AC%E3%83%BC%E3%82%BF_%28%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF%29

無限リストを畳み込む

Prelude> foldr1 (&&) (repeat False)
False
Prelude> foldr1 (&&) (repeat True)
^CInterrupted.
Prelude> foldl1 (&&) (repeat False)
^C^C^C^C^CInterrupted.
foldr1 (&&) (repeat False)
-> (&&) False ((&&) False ((&&) False ....

foldr1 (&&) (repeat True)
-> (&&) True ((&&) True ((&&) True ...

foldl1 (&&) $ repeat False
-> (&&) ((&&) ((&&) ....

$(関数適用)と .(関数合成)

定義

Prelude> :t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
Prelude> :t ($)
($) :: (a -> b) -> a -> b

cf) 中置関数

Prelude> :t (+)
(+) :: Num a => a -> a -> a
Prelude> (+) 3 4
7
Prelude> 3 + 4
7

使用例

Prelude> sum (replicate 5 (max 6.7 8.9))
44.5
Prelude> (sum . replicate 5) (max 6.7 8.9) 
44.5
Prelude> sum . replicate 5 $ max 6.7 8.9
44.5
Prelude> sum $ replicate 5 $ max 6.7 8.9
44.5
独り言)
  なぜ上から2番目が大丈夫かわからない。
  (sum . (replicate 5)) (max 6.7 8.9) ってやらないとダメな気がする。
  コンパイラがsumとreplicateの型をみてよろしくやってるの?
独り言 その2)
  赤津先生に教えていただけました。
  関数合成より関数適用の方が優先度が高いようです。
  f . g xs は f . (g xs)と同値。
  関数合成を優先したい場合は(f . g) xsとする。

cf) 合成関数の話

https://www.shinko-keirin.co.jp/keirinkan/kosu/mathematics/jissen/jissen59.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment