mapM如何与Haskell中的const函数一起使用? [英] How does mapM work with const functions in Haskell?

查看:46
本文介绍了mapM如何与Haskell中的const函数一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我一直在寻找优化密码破解程序的方法时,我遇到了使用该功能的列表中所有可能的字符组合的更短实现:

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]

其中 xs 可能是可用字符,而 n 是所需单词的长度.所以

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

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

将输出列表 ["aaaa","aaab","aaac","aaad","aaba","aabb" .. ,依此类推.只有长度才是右列表中的内容,我可以写成 ['f','h','s','e'] 或任何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.

我可以看到列表为何无关紧要,它已传递给 const 函数.我可以看到列表的 const 在技术上满足了(a-> m a).

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).

但是我的问题是:为什么输出不是简单地 ["abcd","abcd","abcd","abcd"] 或也许是"; abcdabcdabcdabcd&; ? const 函数如何为给定字母输出所有4个字母的变体?

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?

推荐答案

您可以使用以下直觉来理解 mapM :

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]

在您的情况下:

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]

后者等同于列表理解

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

这将产生您的输出.

这篇关于mapM如何与Haskell中的const函数一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆