2017-10-13 118 views
1

所以我有這個功能如何將head(xs)作爲一個參數傳遞給另一個函數?

intCMP :: Int -> Int -> Ordering 
intCMP a b | a == b =EQ 
      | a < b = LT 
      | otherwise = GT 

和定義

xs = [1,2,3] 

我試圖找到有關該列表的信息,但我有troouble傳球元素融入intCMP

這此列表是我想要做的

intCMP head(xs) 1 

但是,這給我和錯誤說它有太多的爭論。

<interactive>:2:9: error: 
     • Couldn't match expected type ‘Int’ with actual type ‘Integer’ 
     • In the first argument of ‘intCMP’, namely ‘(head xs)’ 
     In the expression: intCMP (head xs) 1 
     In an equation for ‘it’: it = intCMP (head xs) 1 
+0

能否請您分享精確的輸出運行你的程序,以及源代碼的統一視圖? –

+0

這就是我所有的源代碼,只是函數和定義的列表。但我會告訴你錯誤。 – christian

+0

'intCMP(head xs)1'和'intCMP head(xs)1'之間存在(或者應該有所不同)。 – chepner

回答

2

錯誤不是關於具有太多參數,而是關於您的列表元素的類型是Integer而不是預期的Int

你有兩個選擇:

第一:讓你的功能比較一般允許所有Ord(可訂購)類型被接受(請注意,此功能可在前奏作爲compare

intCMP :: (Ord a) => a -> a -> Ordering 
intCMP a b | a == b =EQ 
      | a < b = LT 
      | otherwise = GT 

其次,投你的列表元素的類型到一個使用fromIntegral需要:

intCMP (fromIntegral $ head intxs) 1 
1

必須設置括號不同

intCMP (head xs) (head $ tail xs) 

因爲在Haskell功能的應用僅僅是空白。

你的表情被解析爲intCMP head xs head (tail xs)這不是你想要的。

4

在Haskell中,通過鍵入函數的名稱,然後是每個參數來調用函數。參數由空格分隔。

在其他語言中,特別是C的後代,你可以通過在括號中傳入參數來調用方法,但不能在Haskell中調用方法。括號不表示函數調用,它們完全用於修改正常的運算符優先級。

這就像在基本算術中,你有一個正常的運算符優先順序。例如,1 + 2 * 31 + (2 * 3)相同,所以通常不寫後者。但是,如果您希望在乘法之前對加法進行評估,則可以使用括號來表示與標準的偏差:(1 + 2) * 3

這在Haskell中是一樣的。您需要兩個值傳遞給intCMP,你可以這樣做:

Prelude> intCMP (head xs) (head (tail xs)) 
LT 

基本上,你只需要左右移動了一下括號。

+0

,仍然給我一個錯誤 – christian

+1

@christian哪個錯誤?當你做什麼? –

相關問題