我應該編寫帶有這樣的元素的列表,元素和返回位置的函數。像,泛化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