Function 使用累加器的Haskell递归
我试图做一个函数,在给定一个列表的情况下,寻找3个相同和相邻的数字,作为我试图实现的解算器。然后,如果有3个相同和相邻的数字,它会将第一个和第三个相同的数字标记为“0”,并将中间值设置为负值 我想知道为什么这会给我一个错误Function 使用累加器的Haskell递归,function,haskell,recursion,accumulator,Function,Haskell,Recursion,Accumulator,我试图做一个函数,在给定一个列表的情况下,寻找3个相同和相邻的数字,作为我试图实现的解算器。然后,如果有3个相同和相邻的数字,它会将第一个和第三个相同的数字标记为“0”,并将中间值设置为负值 我想知道为什么这会给我一个错误 change xs = chnge xs [] where chnge xs acc | length xs <= 2 = [acc] | (head xs == xs !! 1) && (head xs
change xs = chnge xs []
where
chnge xs acc
| length xs <= 2 = [acc]
| (head xs == xs !! 1) && (head xs == xs !! 2) = [0, (xs !! 1)*(-1), 0] ++ tail xs
| otherwise = chnge (tail xs) (acc ++ head xs)
change xs=chnge xs[]
哪里
chnge xs acc
|长度xs由于acc
是一个列表,我们不想在chnge
的第一个保护中返回[acc]
,而只想返回acc
;类似地,在否则
行中,您不需要acc++头xs
,这意味着xs
是一个列表列表——否则它的第一个成员怎么可能是可追加的?相反地,acc++[head xs]
change xs = chnge xs [] where
chnge xs acc
| length xs <= 2 = acc
| (head xs == xs !! 1) && (head xs == xs !! 2) = [0, (xs !! 1)*(-1), 0] ++ tail xs
| otherwise = chnge (tail xs) (acc ++ [head xs])
一行中三个的大小写可以视为一种模式,因此我们对它们相等的情况做了一个特例。这只是一个分析错误,因为where子句(及其内容)应该比定义change
的子句缩进至少一个空格。一般来说,你应该在问题中包含GHC给你的错误信息。对不起,那是我的错误。我只是忘了缩进代码的其余部分。我已经修复了它,使其符合实际情况。解析错误是由于stackoverflow搞乱了格式,而不是原始源。
change [] = []
change [x] = [x]
change [x,y] = [x,y]
change (x:y:z:ws) | x == y && y == z = 0 : (-y) : 0 : change ws
change (x:xs) = x : change xs
-- *Main> change [12,12,66,66,66,44,44,99,99,99,76,1]
-- [12,12,0,-66,0,44,44,0,-99,0,76,1]