Himanshu Saini
Himanshu Saini

Reputation: 35

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

Upvotes: 1

Views: 605

Answers (1)

shree.pat18
shree.pat18

Reputation: 21757

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

Upvotes: 2

Related Questions