Question

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 ++)?

Was it helpful?

Solution

Doing

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

results in

["HelloHello","GoodbyeGoodbye"]

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

OTHER TIPS

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"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top