2014-04-19 30 views
1

我在Haskell中編寫了一些代碼來學習haskell。它看起來像:第一個Haskell程序

first :: [Int] -> Int -> Int 
first [] x  = x 
first xs y  = y 

我想表達的,我得到一個列表([]或XS)和自變量(X或Y),也不管名單看起來怎麼樣,爭論應該呈現。

所以,當我寫了以下內容:第一[1,2,3] 4,然後ghci的說:

Couldnt match expected type ´a0 -> t´ wth actual type ´[t0]´. Relevant bindings  
include it :: t(boudn at <>:6:1)but its type ´[t 0]´ has none 
In the expression : [1,2,3] 4 
In an equation for ´it´: it = [1,2,3] 4 

我怎樣才能解決這個問題?我犯了什麼錯誤?有人能幫我嗎?

+1

適合我。 – Sibi

+1

如果你根本不關心第一個參數,爲什麼不簡單地'first _ x = x'? – Mat

+0

你寫了'[1,2,3,4] 4'而不是'第一個[1,2,3,4] 4'嗎? –

回答

2

它看起來像你使用[1,2,3,4] 4而不是first [1,2,3,4] 4

> [1,2,3,4] 4 

<interactive>:1:0: 
    Couldn't match expected type `t1 -> t' against inferred type `[a]' 
    In the expression: [1, 2, 3, 4] 4 
    In the definition of `it': it = [1, 2, 3, 4] 4 

順便說一句,你的first定義是一樣的以下內容:

first :: [Int] -> Int -> Int 
first _ x  = x 

這意味着不管第一個參數是什麼,始終返回第二個參數。

+0

我認爲在這種情況下,錯誤報告還將包括:'函數[1,2,3,4 ]應用於一個參數'。 :) – Sibi

+1

@Sibi提問者試圖評估'it = [1,2,3] 4',如錯誤信息的最後一行所示。 –

+0

啊哈,好的...是我從其他編程語言知道的通配符「_」的符號嗎?到你的答案開始:不,我先寫[1,2,3] 4但是我怎樣才能改變沒有通配符的函數聲明? – user3097712