簡體   English   中英

在haskell的類型

[英]Typeclass in haskell

我是haskell的新手,並且正在嘗試實現一個小而簡單的函數,該函數需要兩個字符串並告訴我在同一位置的相同字符的數量。

ed :: (Integral b) => [a] -> [a] -> b
ed _ [] = 0
ed [] _ = 0
ed [] [] = 0
ed (x:xs) (y:ys)
    | x == y = 1 + ed xs ys
    | otherwise = ed xs ys

這不會運行,因為我的類型類定義是錯誤的。 我有兩個字符串,需要返回一個整數,因此我上面寫的類型類定義。 我還需要做些什么嗎?

類型簽名應該是

ed :: (Eq a, Integral b) => [a] -> [a] -> b

這是因為您對ed的定義包括表達式x == y xy都有a型; 為了能夠測試它們的相等性,這種類型必須實現Eq類型類,它提供了==/=運算符。

您收到的錯誤消息將包括以下內容:

 Could not deduce (Eq a) arising from a use of `==' from the context (Integral b) bound by the type signature for ed :: Integral b => [a] -> [a] -> b at /home/dave/tmp/so.hs:(2,1)-(5,26) Possible fix: add (Eq a) to the context of the type signature for ed :: Integral b => [a] -> [a] -> b 

這是試圖告訴你的。

(順便說一下,當字符串長度不同時,你的代碼不處理這種情況。)

由於x == y,您需要添加Eq類型約束:

ed :: (Integral b, Eq a) => [a] -> [a] -> b

您可以注釋掉類型簽名,在ghci中加載模塊並讓它找出類型簽名:

Main> :t ed
ed :: (Eq a1, Num a) => [a1] -> [a1] -> a

暫無
暫無

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

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