elm/exercises/list-ops/ListOps.example

60 lines
965 B
Text
Raw Normal View History

module ListOps exposing (..)
2016-04-18 12:17:26 +00:00
length : List a -> Int
length list =
foldl (\_ acc -> 1 + acc) 0 list
2016-04-18 12:17:26 +00:00
reverse : List a -> List a
reverse list =
foldl (::) [] list
2016-04-18 12:17:26 +00:00
foldl : (a -> b -> b) -> b -> List a -> b
foldl f acc list =
case list of
[] ->
acc
2016-04-18 12:17:26 +00:00
head :: tail ->
foldl f (f head acc) tail
2016-04-18 12:17:26 +00:00
foldr : (a -> b -> b) -> b -> List a -> b
foldr f acc list =
case list of
[] ->
acc
2016-04-18 12:17:26 +00:00
head :: tail ->
f head (foldr f acc tail)
2016-04-18 12:17:26 +00:00
map : (a -> b) -> List a -> List b
map f list =
foldr (\x acc -> f x :: acc) [] list
2016-04-18 12:17:26 +00:00
filter : (a -> Bool) -> List a -> List a
filter f list =
foldr
(\x acc ->
if f x then
x :: acc
else
acc
)
[]
list
2016-04-18 12:17:26 +00:00
append : List a -> List a -> List a
append xs ys =
foldr (::) ys xs
2016-04-18 12:17:26 +00:00
concat : List (List a) -> List a
concat list =
foldr append [] list