[英]How can I add n whitespaces after a string with recursion in Haskell?
For example a number (5) and a string (apple) is given, and the program drops (apple_____).例如给定一个数字 (5) 和一个字符串 (apple),然后程序掉落 (apple_____)。 I want to do this with recursion.
我想用递归来做到这一点。 I tried this way:
我试过这种方式:
add :: Integer -> [Char] -> [Char]
add 0 (x:xs) = (x:xs)
add i [] = add (i-1) [] ++ " "
add i (x:xs) = format (i-1) xs
Given you want to add 0
spaces, you can return the given string (1);给定要加
0
个空格,可以返回给定的字符串(1); if the string is non-empty, you emit the first element of the string x
and recurse on the tail of the string (2);如果字符串不为空,则发出字符串
x
的第一个元素并在字符串的尾部递归 (2); finally if we reached the end of the string, and i
is greater than 0
, we emit a space, and recurse with i
one less than the given i
(3):最后,如果我们到达字符串的末尾,并且
i
大于0
,我们发出一个空格,并递归i
小于给定的i
(3):
add :: Integer -> String -> String
add i xs | i <= 0 = xs -- (1)
add i (x:xs) = x : … -- (2)
add i [] = ' ' : … -- (3)
You here still need to fill in the …
parts.您在这里仍然需要填写
…
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.