簡體   English   中英

Haskell在指定參數類型時引發錯誤

[英]Haskell throws an error while specifying the type of a parameter

我剛剛開始學習Haskell。 我正在嘗試實現一個將數字作為輸入的函數,並根據其值返回-1、0或1。 輸入可以是任何數字(整數或浮點數)。 這是代碼:

signum :: (Num a) => a -> Int
signum x
    | x > 0 = 1
    | x < 0 = -1
    | otherwise = 0

但是,當我嘗試將其加載到ghci中時 ,它顯示以下錯誤:

[1 of 1] Compiling Main             ( run_it.hs, interpreted )

run_it.hs:7:13:
Could not deduce (Ord a) arising from a use of `>'
from the context (Num a)
  bound by the type signature for Main.signum :: Num a => a -> Int
  at run_it.hs:5:11-29
Possible fix:
  add (Ord a) to the context of
    the type signature for Main.signum :: Num a => a -> Int
In the expression: x > 0
In a stmt of a pattern guard for
               an equation for `signum':
  x > 0
In an equation for `signum':
    signum x
      | x > 0 = 1
      | x < 0 = - 1
      | otherwise = 0
Failed, modules loaded: none.

這個錯誤是什么意思?

方法>是在Ord類中定義的,因此您需要在類型簽名中添加一個附加約束:

signum :: (Ord a, Num a) => a -> Int

在GHCi中,您可以使用:i <Class>查看類的方法,例如:

*Main> :i Ord
class Eq a => Ord a where
  compare :: a -> a -> Ordering
  (<) :: a -> a -> Bool
  (<=) :: a -> a -> Bool
  (>) :: a -> a -> Bool
  (>=) :: a -> a -> Bool
  [...]

或者,您可以檢查方法本身:

*Main> :i (>)
class Eq a => Ord a where
  ...
  (>) :: a -> a -> Bool
  ...
    -- Defined in ‘GHC.Classes’
infix 4 >

原始signum沒有此約束的原因是因為它不使用Ord的方法。 相反,它使用專用於有問題的類型的函數(例如ltInt )或模式直接匹配(請參見Word實例): https : ltInt Num.html#signum

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM