首先,我對Haskell是全新的,所以提前感到抱歉,因爲它可能看起來很簡單,但我仍然收到以下錯誤消息:在Haskell中獲取列表的中間元素時發生錯誤
Couldn't match expected type `[a]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for middle :: [a] -> a
at myFile.lhs:18:12
Relevant bindings include
xs :: [a] (bound at myFile.lhs:20:12)
x :: a (bound at myFile.lhs:20:10)
middle :: [a] -> a
(bound at myFile.lhs:19:2)
In the first argument of `(!!)', namely `x'
In the first argument of `div', namely `x !! length xs'
失敗,已加載模塊:無。
嘗試加載:
>middle :: [a] -> a
>middle [] = []
>middle (x:xs) = if (l `mod` 2 == 0) then xs !! (l`div` 2) - 1 else x !! l `div` 2
where l = length xs
如果事情是模糊或不清楚的,請評論。
編輯 因爲採用DIV我得到:
Error: No instance for (Integral a) arising from a use of `div'
Possible fix:
add (Integral a) to the context of
the type signature for middle :: [a] -> a
In the expression: xs !! l `div` 2
In the expression:
if (l `mod` 2 == 0) then xs !! (l `div` 2) - 1 else xs !! l `div` 2
In an equation for `middle':
middle (x : xs)
= if (l `mod` 2 == 0) then
xs !! (l `div` 2) - 1
else
xs !! l `div` 2
where
l = length xs
我認爲DIV問題是,你可能需要額外的括號。有可能你試圖計算div(x !! l)2而不是x! (div l 2)。前者將要求元素類型爲Integral;後者僅需要Int爲整數。 – pigworker