Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Map' higher order Haskell function

I have a list, for example:

["Hello", "Goodbye"]

and I want to use map on the list;

I've successfully used map before:

f = ("example" ++)

so then:

map f ["Hello", "Goodbye"]

Would make the list:

["exampleHello", "exampleGoodbye"]

but how can I use the list items in the function f?

For example, if I wanted to repeat the list element, so

["Hello", "Goodbye"]

would become

["HelloHello", "GoodbyeGoodbye"]

How can I do that with map and a function f (and ++)?

like image 343
James Andrew Avatar asked Dec 05 '22 19:12

James Andrew


2 Answers

Doing

map (\x -> x++x) ["Hello", "Goodbye"]

results in

["HelloHello","GoodbyeGoodbye"]

So f could be defined as f x = (x++x).

like image 188
jeha Avatar answered Jan 04 '23 06:01

jeha


You'd probably want to use a lambda function for this kind of thing. You want to look at each item of the list, and then replace it with itself duplicated. Duplicating a string is easy: \str -> str ++ str, and now you just need to map that function over the list:

map (\x -> x ++ x) ["Hello", "Goodbye"]
like image 27
Jeff Burka Avatar answered Jan 04 '23 06:01

Jeff Burka