Skip to content

Instantly share code, notes, and snippets.

@motokiee
Created October 12, 2015 06:20
Show Gist options
  • Save motokiee/0797d24cf648225e9697 to your computer and use it in GitHub Desktop.
Save motokiee/0797d24cf648225e9697 to your computer and use it in GitHub Desktop.
fold、$演算子、関数合成など。書く(写経)だけでも、より畳み込みの動きとか分かるなぁ。 #CodePiece
sum' :: (Num a) => [a] -> a
sum' xs = foldl (\acc x -> acc + x) 0 xs
sum'' :: (Num a) => [a] -> a
sum'' = foldl (+) 0
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) [] xs
elem' :: (Eq a) => a -> [a] -> Bool
elem' y ys = foldr (\x acc -> if x == y then True else acc) False ys
maximum' :: (Ord a) => [a] -> a
maximum' = foldl1 max
reverse' :: [a] -> [a]
reverse' = foldl(\acc x -> x : acc) []
reverse'' :: [a] -> [a]
reverse'' = foldl (flip (:)) []
product' :: (Num a) => [a] -> a
product' = foldl (*) 1
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr (\x acc -> if p x then x : acc else acc) []
last' :: [a] -> a
last' = foldl1 (\_ x -> x)
and' :: [Bool] -> Bool
and' xs = foldr (&&) True xs
sqrtSum :: Int
sqrtSum = length (takeWhile (<1000) (scanl1 (+) (map sqrt [1..]))) + 1
oddSquareSum :: Integer
oddSquareSum = sum . takeWhile (<10000) . filter odd $ map (^2) [1..]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment