我將通過Get Programming with Haskell,并嘗試擴展一些示例。獲取maxBound列舉的函式有問題:
rotGen :: (Bounded a, Enum a) => a -> (a, Int)
rotGen x = (x, fromEnum (maxBound))
無法從背景關系中使用“maxBound”推斷出 (Bounded a0) : (Bounded a, Enum a)
我理解這個問題 -fromEnum (maxBound)無法弄清楚哪個 Bounded 型別來獲得界限。但我不知道讓編譯器知道it's the same type with x。
我試過fromEnum (maxBound :: a)- 不起作用。
解決了。
供參考。這是Get Programming with Haskell本書第 15 課的 ROT13 旋轉器的更清晰的實作:
-- gen encoder & decoder for enum
rotGen :: forall a . (Bounded a, Enum a) => (a -> a, a -> a)
rotGen = (\x -> toEnum ((half fromEnum x) `mod` max), \x -> toEnum ((upper fromEnum x) `mod` max))
where
max = 1 fromEnum (maxBound @a)
half = max `div` 2
upper = max - half
(盡管正如執行緒中所評論的那樣,語言擴展對于新手來說太高級了)
uj5u.com熱心網友回復:
您可以使用ScopedTypeVariables和TypeApplications擴展名。在這種情況下,我們定義rotGen為:
{-# LANGUAGE ScopedTypeVariables, TypeApplications #-}
rotGen :: forall a . (Bounded a, Enum a) => a -> (a, Int)
rotGen x = (x, fromEnum (maxBound @a))
有了 ,ScopedTypeVariables我們可以a在運算式中使用型別引數,我們應該使用一個顯式的forall. 該TypeApplication擴展將指定我們用什么實體的maxBound常數。
uj5u.com熱心網友回復:
如果您出于某種原因不想使用擴展,則可以asTypeOf改用:
rotGen x = (x, fromEnum (maxBound `asTypeOf` x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359155.html
標籤:哈斯克尔
下一篇:僅回傳字串串列中的元音
