我需要这样的东西:
[[i]++[j]| i <- ['a'..'d'], j <- ['a'..'d']] where I get the output:
["aa","ab","ac","ad","ba","bb","bc","bd","ca","cb","cc","cd","da","db","dc","dd"]
我需要的是一种更动态的生成此输出数组的方法。因此,如果得到一个整数值3我应该看起来像:
[[i]++[j]++[k]| i <- ['a'..'d'], j <- ['a'..'d'], k <- ['a'..'d']
答案 0 :(得分:6)
replicateM n ['a'..'d']
n
是重复的次数。
答案 1 :(得分:2)
澄清Louis Wasserman的答案:
replicateM i m
相当于:
do a1 <- m
a2 <- m
a3 <- m
...
ai <- m
return [a1, a2, a3, ..., ai]
例如,replicateM 3 getLine
是一个IO [String]
操作,它将获得三行并为您提供字符串列表:
do line1 <- getLine
line2 <- getLine
line3 <- getLine
return [line1, line2, line3]
现在,请记住,列表推导只是花哨的语法[] Monad
:
[[i, j] | i <- ['a'..'d'], j <- ['a'..'d']]
=
do i <- ['a'..'d']
j <- ['a'..'d']
return [i, j]
这正是replicateM 2 ['a'..'d']
的样子。
答案 2 :(得分:0)
您可以使用以下
seq i xs | i > 0 = [x:ys | x <- xs, ys <- seq (i-1) xs]
| otherwise = [[]]