Skip to content

Instantly share code, notes, and snippets.

@songpp
Created April 2, 2011 07:45
Show Gist options
  • Save songpp/899314 to your computer and use it in GitHub Desktop.
Save songpp/899314 to your computer and use it in GitHub Desktop.
haskell基础复习巩固
-- fold left
foldLeft :: (b -> a -> b) -> b -> [a] -> b
foldLeft _ acc [] = acc
foldLeft f acc (x : xs) = foldLeft f (f acc x) xs
-- fold right
foldRight :: (a -> b -> b) -> b -> [a] -> b
foldRight f acc [] = acc
foldRight f acc (x : xs) = f x (foldRight f acc xs)
length' :: [a] -> Int
length' = foldLeft (\acc _ -> acc +1) 0
sum' = foldLeft (+) 0
reverse' :: [a] -> [a]
reverse' = foldLeft (\acc x -> x : acc) []
map' :: (a -> b) -> [a] -> [b]
map' f = foldRight (\x acc -> f x : acc) []
filter' :: [a] -> (a -> Bool) -> [a]
filter' [] _ = []
filter' (x:xs) f
| f x = x : filter' xs f
| otherwise = filter' xs f
(+=+) :: [a] -> [a] -> [a]
xs +=+ ys = foldRight (:) ys xs
zip' :: [a] -> [b] -> [(a,b)]
zip' (x : xs) (y : ys) = (x , y) : zip' xs ys
zip' _ _ = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment