字符串的列表 - haskell?

时间:2014-02-26 17:19:27

标签: haskell map repeat

我试图获取整数列表并重复多次,但是作为haskell中的字符串。预期的输出是:

> nnn [3,1,5] = ["3-3-3","1","5-5-5-5-5"]
> nnn [10,2,4] = ["10-10-10-10-10-10-10-10-10-10","2-2","4-4-4-4"]

现在我觉得我很接近......但是我不能把一个整数列表变成一个字符串,并且绝对不知道如何处理连字符。这是我到目前为止的代码,输出:

nnn :: [Int] -> [[Char]]
nnn list = map show (map (\x -> take x $ repeat x) list)

它给了我:

> nnn [3,1,5] = ["[3,3,3]","[1]","[5,5,5,5,5]"]

(我至少接近!)有人能指出我正确的方向来看这里吗? :)

1 个答案:

答案 0 :(得分:7)

单独的函数将数字重复到连字符分隔的字符串中似乎很有用。首先将数字转换为字符串,然后复制它,并使用intercalate在每个元素之间插入连字符并加入它们:

repeatNumber :: Int -> String
repeatNumber n = intercalate "-" $ replicate n $ show n

然后nnn很简单:

nnn :: [Int] -> [String]
nnn = map repeatNumber

replicate a btake a $ repeat b