Haskell 函数虚无中的非穷举模式
所以,我的问题是,我必须编写一个程序来过滤列表中的所有3*x(3,6,9…)元素。我的程序看起来像:Haskell 函数虚无中的非穷举模式,haskell,Haskell,所以,我的问题是,我必须编写一个程序来过滤列表中的所有3*x(3,6,9…)元素。我的程序看起来像: length' :: [a] -> Int length' = foldr (\_ -> (+1)) 0 help_ :: [a] -> [a] -> [a] help_ (x:xs) [] = help_ (xs) [x] help_ [] (x) = (x) help_ (x:xs) (y) |((length' [xs]) ==0) = (y)
length' :: [a] -> Int
length' = foldr (\_ -> (+1)) 0
help_ :: [a] -> [a] -> [a]
help_ (x:xs) [] = help_ (xs) [x]
help_ [] (x) = (x)
help_ (x:xs) (y)
|((length' [xs]) ==0) = (y)
|((length' [y]) `mod` 2 ==0) = help_ (xs) (y)
|otherwise = help_ (xs) (y++[x])
noThirds :: [a] -> [a]
noThirds [x] = help_ [x] []
编译器接受这一点,但在我输入时给出错误“函数noThirds中的非穷举模式”
“没有鸟[1,2,3,4,5,6,7,8]”
. 我想这是因为我错过了各种各样的“帮助”,但我不明白。我感谢你的帮助!
顺便说一句,不允许使用预定义的列表和算术函数。这是因为
nothird
只有一个模式,[x]
,它只与单个元素列表匹配。
[x]
完全等同于(x:[])
。我想你的意思是
noThirds :: [a] -> [a]
noThirda xs = help_ xs []
jozefg已经回答了你的问题。我会指出更多的事情 当心!表情
((length' [xs]) ==0)
((length' [y]) `mod` 2 ==0)
评估
(1 ==0)
(1 `mod` 2 ==0)
所以他们都是假的。你想要什么
((length' xs) ==0)
((length' y) `mod` 2 ==0)
此外,在类似这样的函数中,计算长度通常会导致性能低下,并且被认为是糟糕的风格。考虑以这种方式预处理列表,而不是
addPosition :: [a] -> [(Int,a)]
addPosition xs = go 0 xs
where go n [] = ...
go n (y:ys) = ...
-- Example: addPosition [33,66,20] ===> [(0,33),(1,66),(2,20)]
-- This is equivalent to (zip [0..]) but we can not use list functions.
然后,添加一些后处理以过滤所需元素:现在更容易了,因为每个元素都按其位置进行了标记。列表的结构是:
- 空列表[]
- 或者一个元素后跟列表的其余部分(x:xs)
noThirds :: [Int] -> [Int]
noThirds xs = noThirds' xs 1
noThirds' :: [Int] -> Int -> [Int]
noThirds' [] _ = []
noThirds' (x:xs) i
| i `mod` 3 == 0 = rest
| otherwise = x : rest
where
rest = noThirds' xs (succ i)
现在不需要计算列表的长度
关于H-99解决方案16的更多答案:99个Haskell问题:
哦,非常感谢,我想说我收到了一条奇怪的消息,但后来我看到你写了“noThirda xs”,傻我哈哈,这很有帮助,现在我只需要找出代码中有什么地方不对劲:)
noThirds :: [Int] -> [Int]
noThirds xs = noThirds' xs 1
noThirds' :: [Int] -> Int -> [Int]
noThirds' [] _ = []
noThirds' (x:xs) i
| i `mod` 3 == 0 = rest
| otherwise = x : rest
where
rest = noThirds' xs (succ i)