简体   繁体   中英

Foldr and Foldl function in haskell

There is code of fold function in Haskell programming.

map' ::(a->b)->[a]->[b]
map' f xs=foldr(\x acc ->f x:acc)[] xs

INPUT:

map' (+3) [1,2,3]

OUTPUT:

[4,5,6]

It takes the element from right side due to foldr function and I Want to take the element from left side and append into list and i want a output [6,5,4].i did it through foldl function but it gives error.

ERROR: Couldn't match expected type `a' with actual type `[b]'
      `a' is a rigid type variable bound by
          the type signature for map' :: (a -> b) -> [a] -> [b]
          at doubleme.hs:1:8
    In the first argument of `f', namely `x'
    In the first argument of `(:)', namely `f x'
    In the expression: f x : acc

Change your function signature to map' ::(a->b)->[a]->[b] .

The map operation basically takes a function that transforms an element of type 'a' to an element of type 'b', and a list of elements of type 'a', to produce a list of elements of type 'b' using the transforming function. Your function signature containing another type 'c' is contrary to this, because 'b' and 'c' cannot implicitly be assumed to be the same type.

Next, to use foldl , you have to reverse the order of your input parameters, like so:

map' :: (a->b)->[a]->[b]
map' f xs = foldl (\acc x ->f x:acc) [] xs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM