Kau*_*Kau 2 haskell functional-programming list
我对 Haskell 很陌生。我已经挣扎了很长时间,并尝试了我能想到的一切。我希望该函数执行的是检查第一个非零元素,将其减 1,然后根据它在列表中的位置(最后一个元素从位置 1 开始)增加下一个元素。例如:
示例 1:
[9,0,0,0,0,0,0,0,0] -> [8,8,0,0,0,0,0,0,0] increments the next element by 8 since it's at position 8
Run Code Online (Sandbox Code Playgroud)
示例 2:
[0,0,0,0,0,0,0,3,1] -> [0,0,0,0,0,0,0,2,2] increments the next element by 1 since it's at position 1
Run Code Online (Sandbox Code Playgroud)
示例 3:
[0,0,3,2,0,0,0,0,0] -> [0,0,2,8,0,0,0,0,0] increments the next element by 6 since it's at position 6
Run Code Online (Sandbox Code Playgroud)
我的代码适用于上述所有情况,但最后一个元素不为零的情况除外。例如:
[0,0,0,0,0,0,0,0,5] should return [0,0,0,0,0,0,0,0,4] but it gives me the error 'empty list.'
Run Code Online (Sandbox Code Playgroud)
我知道我需要有一个条件来检查我的列表的长度是否为 1,如果是,它应该只将当前元素减一(并且不增加下一个元素,因为没有一个)。我只是不知道该怎么做。到目前为止,这是我的代码:
chop :: [Int] -> [Int]
chop [] = []
chop (x:xs) =
if x > 0
then [x-1] ++ [head xs + length xs] ++ drop 1 xs
else [x] ++ chop xs
Run Code Online (Sandbox Code Playgroud)
一种直接的方法是添加第三种模式:
chop [] = []
chop [x] = -- TODO
chop (x:xs) = -- as before
Run Code Online (Sandbox Code Playgroud)
如果你这样做,你可以考虑让你的第三个模式匹配第一个元素:
chop [] = []
chop [x] = -- TODO
chop (x:x':xs) =
if x > 0
then [x-1] ++ [x' + length xs + 1] ++ xs
else [x] ++ chop (x':xs)
Run Code Online (Sandbox Code Playgroud)
另一种方法是使您的x:xs模式的代码即使在xs为空时也能工作,使用take 1代替head:
chop (x:xs) =
if x > 0
then [x-1] ++ map (length xs+) (take 1 xs) ++ drop 1 xs
else [x] ++ chop xs
Run Code Online (Sandbox Code Playgroud)
顺便说一句,习惯上,人们通常会写foo:bar而不是[foo] ++ bar尽可能地写(除了少数例外):
chop (x:xs) =
if x > 0
then x-1 : head xs + length xs : drop 1 xs
else x : chop xs
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |