gpt4 book ai didi

haskell - 如何使用 Haskell 中的 Bounded 类型类来定义具有浮点范围的类型?

转载 作者:行者123 更新时间:2023-12-03 14:01:03 25 4
gpt4 key购买 nike

由于违反了 minBound 和 maxBound,我预计以下代码会因类型错误而失败。但是,正如您所看到的,它通过并没有标记错误。

{-# OPTIONS_GHC -XTypeSynonymInstances #-}
module Main where

type Probability = Float
instance Bounded Probability where
minBound = 0.0
maxBound = 1.0

testout :: Float -> Probability
testout xx = xx + 1.0

main = do
putStrLn $ show $ testout 0.5
putStrLn $ show $ testout (-1.5)
putStrLn $ show $ testout 1.5

在前奏曲中我明白了
*Main> :type (testout 0.5)
(testout 0.5) :: Probability

在提示符下,我得到了这个:
[~/test]$runhaskell demo.hs
1.5
-0.5
2.5

显然,我没有正确声明 Bounded,而且我确定我在语法上做错了什么。 Google 上没有太多关于有界类型类的简单内容,因此我们将不胜感激。

最佳答案

那不是Bounded是为了。 Bounded a只定义函数minBound :: amaxBound :: a .它不会引起任何特殊检查或任何事情。

您可以使用所谓的智能构造函数定义有界类型。那是:

module Probability (Probability) where

newtype Probability = P { getP :: Float }
deriving (Eq,Ord,Show)

mkP :: Float -> Probability
mkP x | 0 <= x && x <= 1 = P x
| otherwise = error $ show x ++ " is not in [0,1]"

-- after this point, the Probability data constructor is not to be used

instance Num Probability where
P x + P y = mkP (x + y)
P x * P y = mkP (x * y)
fromIntegral = mkP . fromIntegral
...

所以制作 Probability 的唯一方法是使用 mkP最终函数(当您使用给定 Num 实例的数字运算时,这将为您完成),它检查参数是否在范围内。由于模块的导出列表,在这个模块之外是不可能构造无效概率的。

可能不是您正在寻找的两类轮船,但哦,好吧。

为了获得额外的可组合性,您可以通过制作 BoundCheck 来排除此功能。模块而不是 Probability .和上面一样,除了:
newtype BoundCheck a = BC { getBC :: a }
deriving (Bounded,Eq,Ord,Show)

mkBC :: (Bounded a) => a -> BoundCheck a
mkBC x | minBound <= x && x <= maxBound = BC x
| otherwise = error "..."

instance (Bounded a) => Num (BoundCheck a) where
BC x + BC y = mkBC (x + y)
...

因此,当您提出问题时,您可以获得您希望内置的功能。

要执行此派生内容,您可能需要语言扩展 {-# LANGUAGE GeneralizedNewtypeDeriving #-} .

关于haskell - 如何使用 Haskell 中的 Bounded 类型类来定义具有浮点范围的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4557394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com