0

我需要这样的东西:

[[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']
4

3 回答 3

6
replicateM n ['a'..'d']

n是重复的次数。

于 2013-10-27T18:29:42.260 回答
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']看起来的样子。

于 2013-10-28T09:07:53.247 回答
0

你可以使用以下

seq i xs | i > 0 = [x:ys | x <- xs, ys <- seq (i-1) xs]
         | otherwise = [[]]
于 2013-10-31T04:43:24.557 回答