Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

constants - How does mapM work with const functions in Haskell?

as I had been looking for ways to optimize a password cracker I had been making, I came across a much shorter implementation of all possible character combinations in a list, which used this function:

mapM (const xs) [1..n]

where xs could be the characters available, and n the length of the desired words. so

mapM (const "abcd") [1..4]

would output a list ["aaaa","aaab","aaac","aaad","aaba","aabb"..] and so on. Only the length matters for the list of th right, I could have written ['f','h','s','e'] or any 4 element list instead.

I can see why the list doesn't matter, it's passed to a const function. I can see that const of a list technically satisfies (a -> m a).

But my question is: why isn't the output simply ["abcd","abcd","abcd","abcd"], or maybe "abcdabcdabcdabcd"? What does a const function do to output all 4 letter variations for the given letters?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can understand mapM using this intuition:

mapM f [x1, x2, ..., xN]
=
do y1 <- f x1
   y2 <- f x2
   ...
   yN <- f xN
   return [y1, y2, ..., yN]

In your case:

mapM (const "abcd") [1 .. 4]
=
do y1 <- const "abcd" 1
   y2 <- const "abcd" 2
   y3 <- const "abcd" 3
   y4 <- const "abcd" 4
   return [y1, y2, y3, y4]
=
do y1 <- "abcd"
   y2 <- "abcd"
   y3 <- "abcd"
   y4 <- "abcd"
   return [y1, y2, y3, y4]

The latter is equivalent to a list comprehension

[ [y1, y2, y3, y4] | y1<-"abcd", y2<-"abcd", y3<-"abcd", y4<-"abcd"]

which will produce your output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...