gpt4 book ai didi

haskell - 如何检查您是否处于 Haskell 循环的第一次迭代中?

转载 作者:行者123 更新时间:2023-12-05 09:15:27 26 4
gpt4 key购买 nike

如果这个问题没有真正阐明我的问题,我可以理解,所以这里有更多的解释:

我试图在我的字符串的开头添加字符串“+”,我得到的是这样的:

printLine :: [Int] -> String  --Type of the function
printLine [] = "" --Base case

printLine (x:xs) = "+" ++ foldr (++) "+" f ++ printLine xs
where f = replicate x "-"

我从上面得到的结果:

+-----++------++------++------+

我想得到的结果:

+-----+------+------+------+

基本上我的问题是:如何只在开头添加“+”?我能理解这可能是一个愚蠢的问题,但我现在被困了一段时间,我无法在 SO 或其他地方找到答案。

最佳答案

建议:在第一次迭代时不要检测,这很难;而是检测您何时处于最后一次迭代中,这很容易,因为它是第一行中的 [] 情况。

printLine :: [Int] -> String
-- final iteration; add an extra + at the end
printLine [] = "+"

-- not the final iteration; don't include a + at the end of the -s
printLine (x:xs) = "+" ++ replicate x '-' ++ printLine xs

关于haskell - 如何检查您是否处于 Haskell 循环的第一次迭代中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52431915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com