i create "map lookup" function using folds.
this "map" (just list of tuples):
phonebook:: [([char], [char])] phonebook = [("bob", "00-21-55") ,("jack", "55-51-55") ,("joe", "10-61-25") ,("susy", "06-21-55") ,("clara", "50-31-95") ] and kind of function write:
lookup :: (eq k) => k -> [(k,v)] -> v lookup k = foldl1 (\acc (x,y) -> if k == y y else acc) however, not compile, yields "cannot construct infinite type" error.
could explain why wrong , how can make work?
please note aware of data.map , map functions exports, want solely learn how folds work.
first here working version - i'll come , explain in few minutes:
lookup :: (eq k) => k -> [(k,v)] -> maybe v lookup k = foldl (\ acc (k',v) -> if k == k' v else acc) nothing the problems have are:
- for
foldl1have typefoldl1 :: (a -> -> a) -> [a] -> aneed same type elements , result - here want value result fold on tuples of key/value-pairs. - this why switched more general
foldl(note not interested in if right choice here - seefoldl'vsfoldlvsfoldr) - this function can never total (if key not in dictionary/key-value-pair-list) opted reflect in result type,
maybe v- of course makes easy find initial value:nothing
if don't maybe part can use error instead too:
lookup :: (eq k) => k -> [(k,v)] -> v lookup k = foldl (\ acc (k',v) -> if k == k' v else acc) (error "key not found") remarks:
this not efficient implementation through of list no matter if found key yet - feel free try come
hint: haskell lazy - maybe can find filtering out right key/value-pairs, taking safe-head of , maping value-part ;) )
Comments
Post a Comment