當我評估運算式時,
snd (True, [2,[5]])
編譯器說:
? Non type-variable argument in the constraint: Num [a]
(Use FlexibleContexts to permit this)
? When checking the inferred type
it :: forall a. (Num a, Num [a]) => [[a]]
我該如何解決?對我來說,snd應該根據其簽名處理任何元組型別,但也許不是這樣。
uj5u.com熱心網友回復:
問題在于表達[2,[5]]。無效的原因與無效的原因相同['x',True]:在 Haskell 中,串列的所有元素必須屬于同一型別。
你得到一個神秘的錯誤訊息[2,[5]]而不是產生的簡單錯誤訊息的Couldn't match expected type ‘Char’ with actual type ‘Bool’原因['x',True]是 Haskell 中的數字文字是多型的,所以如果你在范圍內有一個非常奇怪(并且可能是非法的)Num實體,那么它在技術上是可以創建的并使用這種型別;它幾乎肯定不會做你想做的事。
只是為了好玩,這是一個你寫的東西是有效的案例(而且這些例子甚至是合法的):
{-# LANGUAGE ExtendedDefaultRules, FlexibleContexts, FlexibleInstances #-}
instance Num () where
_ _ = ()
_ * _ = ()
abs _ = ()
signum _ = ()
fromInteger _ = ()
_ - _ = ()
instance Num [()] where
( ) = ( )
(*) = (*>)
abs = id
signum _ = [()]
fromInteger x
| x >= 0 = replicate (fromInteger x) ()
| otherwise = error "if Natural can bottom here, so can this"
xs - [] = xs
(_:xs) - (_:ys) = xs - ys
[] - (_:_) = error "if Natural can bottom here, so can this"
main :: IO ()
main = print $ snd (True, [2,[5]])
它列印[[(),()],[()]]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532467.html
標籤:哈斯克尔
上一篇:為什么這些HaskellParsec組合子的順序很重要?
下一篇:如何將多個值傳遞給一元函式
