3

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

Will Ness
  • 70,110
  • 9
  • 98
  • 181
James Andrew
  • 7,197
  • 14
  • 46
  • 62
  • 2
    I don't know if it helps you, but `f = ("example" ++)` is just a shorthand for `f x = "example" ++ x`. –  Oct 23 '11 at 17:26
  • @delnan it's actually a shorthand for `f = (\x -> "example" ++ x)` rather than `f x = "example" ++ x`, isn't it? These are not always quite the same thing when it comes to optimizations. – leftaroundabout Oct 23 '11 at 17:41
  • 1
    @leftaroundabout: Semantically, they are the same (the monomorphism restriction would have ruined the day, but in this case the type is monomorphic anyway, due the string literal) and that's all that matters here. I don't know whether or not there is a difference regarding optimization, and OP shouldn't care. –  Oct 23 '11 at 17:44

2 Answers2

8

Doing

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

results in

["HelloHello","GoodbyeGoodbye"]

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

jeha
  • 10,562
  • 5
  • 50
  • 69
  • 8
    Let's see... can we do this _only_ using confusing type-class functions? Why, yes! `liftM (join mappend) (mappend (return "Hello") (return "Goodbye")) :: [String]` – Daniel Wagner Oct 23 '11 at 19:13
6

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"]
Jeff Burka
  • 2,571
  • 1
  • 17
  • 30
  • Thanks for suggestion, works fine, but not exactly what I wanted :) -will be doing much complicated stuff with the lists in future, but wanted to know how to involve the elements basically first. Thanks anyway. :) – James Andrew Oct 23 '11 at 17:29