Generics 推广haskell函数
我应该写一个函数,该函数接受列表、元素和返回位置,并使用这样的元素。像Generics 推广haskell函数,generics,haskell,Generics,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 ->
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
函数来实现它。findFirstPosition的类型应该是
findFirstPosition :: Eq a => a -> [a] -> Maybe Int
此函数的目的是查找位置或索引。因此,返回类型应该封装适合索引的内容,但与参数类型无关
无关:您确定索引应该以1开头吗?通常是基于0的索引。您可以使用列表理解更精确地实现这一点
pos :: Eq a => a -> [a] -> [Int]
pos y xs = [i | (i, x) <- zip [0..] xs, y == x]
pos::Eq a=>a->[a]->[Int]
POS Y-XS= = [i](i,x)注释:请用空格缩进代码,而不是标签(至少在这里,代码格式化程序在这里根本不喜欢标签)。一些改进的提示:让我们考虑下面的表达式<代码> CONTAT[ [ FROWALRES RE],MAP(\A+> A+(FROWALRES))(POS VALL(DROP(FROWALRES)XS))
。此表达式的形式为concat[[e1],e2]
。检查这种形式的参数的concat
结果。此外,您可以为表达式fromJust res
定义一个短名称,因为它多次出现。@Jan Christiansen,谢谢,我会这样做。这只是练习,所以它实际上不符合基本要求)我会尽快接受这个答案。Thanks,但实际上我应该在这个任务中使用find
。很抱歉我没有提到这个。