我应该编写带有这样的元素的列表,元素和返回位置的函数。像,泛化haskell函数
pos 2 [1, 2, 3, 2] -> [2, 4]
pos 1 [1, 2, 3, 2] -> [1]
pos 8 [1, 2, 3, 2] -> []
这就是我所做的。
--findFirstPosition :: Eq a => a -> [a] -> Maybe a
findFirstPosition val xs = case f of
Nothing -> Nothing
Just (v, i) -> Just(i)
where f = (find (\ (v, i) -> val == v) (zip xs [1..]))
--pos :: Eq a => a -> [a] -> [Int]
pos _ [] = []
pos val xs = if (finded)
then concat[
[fromJust res],
map (\a -> a + (fromJust res))
(pos val (drop (fromJust res) xs))]
else []
where
res = findFirstPosition val xs
finded = (isJust res)
它的作品相当不错。但是当我尝试使用函数类型(如评论中所示)时发生错误
Could not deduce (a ~ Int)
from the context (Eq a)
bound by the type signature for pos :: Eq a => a -> [a] -> [Int]
at \test.hs:(63,1)-(72,29)
`a' is a rigid type variable bound by
the type signature for pos :: Eq a => a -> [a] -> [Int]
at \test.hs:63:1
Expected type: Maybe Int
Actual type: Maybe a
In the first argument of `fromJust', namely `res'
In the first argument of `drop', namely `(fromJust res)'
我应该如何处理它?此外,任何额外的代码审查意见,高度赞赏。
Upd 我应该使用find
函数来实现它。
注意:请使用空格缩进代码,而不是制表符(至少在这里,这里的代码格式化程序根本不喜欢标签)。 – 2012-01-07 14:14:02
改进的一些提示:让我们考虑下面的表达式'concat [[fromJust res],map(\ a - > a +(fromJust res))(pos val(drop(fromJust res)xs))]''。该表达式具有'concat [[e1],e2]'的形式。检查'concat'对于这种形式的参数的收益。此外,您可以为“fromJust res”表达式定义一个短名称,因为它会多次出现。 – 2012-01-07 16:10:40
@Jan Christiansen,谢谢我会做。 – 2012-01-07 17:34:45