Haskell:将Int转换为长度为n的字符串

问题描述 投票:0回答:1

这里是Haskell初学者。

我有一个整数[1..n]的列表,想将它们转换成一个String,其中每个数字占用3个空格。示例:

[6..12] becomes
" 6  7  8  9 10 11 12"

所以一位数字被两个空格包围,而两位数字前面只有一个空格。

[使用unwords(和show将Ints转换为字符串)显然仅在每个数字之间设置一个空格。

有人知道如何实现吗?非常感谢您的任何建议。

haskell functional-programming
1个回答
0
投票

谢谢您的评论。我不知道为什么以前没有想到这一点,但现在我写了一个像Ry-建议的函数。

spaces i 
  | length (show i) == 1 = “ “ ++ show i ++ “ “
  | length (show i) == 2 = “ “ ++ show i
  | otherwise = show i 

然后我将其映射到列表的每个元素并将其串联(n在函数中定义)

function :: Int -> String
function n = concat (map spaces [1..n])
© www.soinside.com 2019 - 2024. All rights reserved.