Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map function using foldl or foldr in Haskell

Tags:

haskell

I am writing a function my_map which takes a unary function and a list and returns the list resulting from mapping the function over all elements of the input list.

Main> my_map (^3) [1..5]

[1,8,27,64,125]

I tried it like this:

my_map :: (a -> b) -> [a] -> [b]
my_map f [] = []
my_map f (x:xs) = foldr (\x xs -> (f x):xs) [] xs

But after running above, I get only [8,27,64,125]. the first number 1 is not displaying in output.

Can anybody help me?

like image 645
Kushal Shinde Avatar asked Dec 01 '25 03:12

Kushal Shinde


1 Answers

You are using the (x:xs) pattern in your arguments, but when you apply the fold, you only apply it to the xs part, which means your first element i.e. the one that x represents never gets processed. You need to change it to this:

my_map :: (a -> b) -> [a] -> [b]
my_map f xs = foldr (\y ys -> (f y):ys) [] xs

Since you are using foldr, you do not need to explicitly handle the empty list case. Moreoever, you do not need to specify the list in (x:xs) format.

Finally, my own preference is to avoid using the same name for function inputs and any helper functions or expressions in the function definition.That is why, I have used xs for the input list and y and ys for the parameters passed to the lambda.

like image 68
shree.pat18 Avatar answered Dec 02 '25 16:12

shree.pat18



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!