2

I have some chars, for example ["ab"], and I just have two number, zero and one. And I want to get an answer like

[[('a', 1), ('b', 1)],
 [('a', 0), ('b', 1)],
 [('a', 1), ('b', 0)],
 [('a', 0), ('b', 0)]]

I am a beginner, could someone help me?

Thankyou very much.

lpy
  • 587
  • 1
  • 6
  • 20

1 Answers1

4

The most interesting part is generating the list of all possible sequences of 0 and 1; one way is via replicateM:

> replicateM 2 [1,0]
[[1,1],[1,0],[0,1],[0,0]]

You can use map and zip from there:

> map (zip "ab") (replicateM 2 [1,0])
[[('a',1),('b',1)],[('a',1),('b',0)],[('a',0),('b',1)],[('a',0),('b',0)]]

To match your answer exactly, you'd have to do a tiny bit of extra munging:

> map (zip "ab" . reverse) (replicateM 2 [1,0])
[[('a',1),('b',1)],[('a',0),('b',1)],[('a',1),('b',0)],[('a',0),('b',0)]]
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • Thankyou, but I still can't understand, what if it is "abcd"? Does it still work? – lpy May 07 '12 at 06:42
  • 1
    @Laurent You may use [Hoogle](http://www.haskell.org/hoogle/) to find functions by name or type. If you want to match up with different strings, you will need some minor changes: the `2` argument to `replicateM` should be the length of the string. – Daniel Wagner May 07 '12 at 06:57
  • Thankyou all of you! I will remember this website, it works well, thankyou for your help. – lpy May 07 '12 at 07:09