2015-05-17 14 views
1

首先,我對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 
+1

我認爲DIV問題是,你可能需要額外的括號。有可能你試圖計算div(x !! l)2而不是x! (div l 2)。前者將要求元素類型爲Integral;後者僅需要Int爲整數。 – pigworker

回答

1

注意x只是一個元素,而不是一個列表。所以,使用x !! anything是一個類型錯誤。你的意思是xs !! anything

此外,

middle [] = [] 

是錯誤的,因爲你必須返回一個元素,而不是一個列表。由於沒有中間元素,我們只能返回底部,例如

middle [] = error "middle: empty list" 

上面使得功能的部分之一,即,如果在調用與空列表的功能的更大的程序,該程序將崩潰。

如果要禁止,你可以將類型更改爲Maybe

middle :: [a] -> Maybe a 
middle []  = Nothing 
middle (x:xs) = Just (.....) 
+0

另外,當[a] - > a是Num和* div *需要Integral時,我該如何解決它。我編輯了我的問題 – user8

+0

@ user4325010也許你缺少括號,試試''xs !! (l'div' 2)'' – chi