2012-01-07 49 views
1

我应该编写带有这样的元素的列表,元素和返回位置的函数。像,泛化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函数来实现它。

+0

注意:请使用空格缩进代码,而不是制表符(至少在这里,这里的代码格式化程序根本不喜欢标签)。 – 2012-01-07 14:14:02

+1

改进的一些提示:让我们考虑下面的表达式'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

+0

@Jan Christiansen,谢谢我会做。 – 2012-01-07 17:34:45

回答

2

类型的findFirstPosition应该是

findFirstPosition :: Eq a => a -> [a] -> Maybe Int 

此功能的目的是要找到一个位置,或索引。所以返回类型应该包含适合于索引的东西,但与参数类型无关。

无关:你确定索引应该从1开始?通常是基于0的索引。

+0

是的。非常感谢。 – 2012-01-07 14:16:52

+0

这只是练习,所以它不会真正与基础米)我会尽快接受这个答案。 – 2012-01-07 14:21:24

1

您可以使用列表理解更加合理地实现这一点。

pos :: Eq a => a -> [a] -> [Int] 
pos y xs = [i | (i, x) <- zip [0..] xs, y == x] 

我也改成了使用基于0指数与其他列表功能的一致性,但是如果你需要,你可以轻松地调整这基于1。

+0

你有没有注意到这个问题被标记为家庭作业? – is7s 2012-01-07 19:57:28

+0

谢谢,但实际上我应该在这个任务中使用'find'。对不起,我没有提到这一点。 – 2012-01-07 20:12:14