Real World Haskell - 第4章 Part4 How to think about loops (続き)
Real World Haskell で Haskell を継続的に勉強中。
Chapter 4. Functional programming
Chapter 4. Functional programming
How to think about loops
- for/while ループは Haskell には存在しないので別の方法で表現する必要がある
Selecting pieces of input
oddList :: [Int] -> [Int] oddList (x:xs) | odd x = x : oddList xs | otherwise = oddList xs oddList _ = []
- このような操作はイディオムなので filter :: (a -> Bool) -> [a] -> [a] が使える
ghci> filter odd [3,1,4,1,5,9,2,6,5] [3,1,1,5,9,5]
Computing one answer over a collection
- this is a “natural” way to represent a loop in a pure functional language.
mySum xs = helper 0 xs where helper acc (x:xs) = helper (acc + x) xs helper acc _ = acc
adler32_try2 xs = helper (1,0) xs where helper (a,b) (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base b' = (a' + b) `mod` base in helper (a',b') xs helper (a,b) _ = (b `shiftL` 16) .|. a