3

我正在尝试创建一个函数,该函数将在给定列表的情况下查找 3 个相同和相邻的数字,用于我正在尝试实现的求解器。然后,如果有3个相同和相邻的数字,它将第1个和第3个相同的数字标记为'0',并将中间值设置为负数。

我想知道为什么这给了我一个错误。:

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)
4

1 回答 1

9

由于acc是一个列表,我们不想[acc]在 的第一个守卫中返回chnge,而只是acc; 同样在otherwise你不想要的那一行中acc ++ head 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])

这似乎有点不对劲,但真正的问题是缺乏“模式匹配”以及 , 和 的head危险tail使用!!。尝试更多类似的东西,也许?(虽然它不使用累加器):

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]

连续三个的情况可以被认为是一种模式,因此我们为它们相等的情况做一个特殊的情况。

于 2012-10-04T23:33:59.200 回答