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

ram*_*jan 16 haskell types typeclass

由于违反了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
Run Code Online (Sandbox Code Playgroud)

在序曲中我得到了这个

*Main> :type (testout 0.5)
(testout 0.5) :: Probability
Run Code Online (Sandbox Code Playgroud)

在提示我得到这个:

[~/test]$runhaskell demo.hs
1.5
-0.5
2.5
Run Code Online (Sandbox Code Playgroud)

很明显,我没有正确宣布有限,我确信我在语法上做错了.谷歌关于有界类型类没有太多简单的东西,所以任何帮助都会非常感激.

luq*_*qui 23

这不是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
    ...
Run Code Online (Sandbox Code Playgroud)

因此,制作a的唯一方法ProbabilitymkP最终使用该函数(这是在您使用给定我们的Num实例的数值运算时为您完成的),它检查参数是否在范围内.由于模块的导出列表,在此模块之外是不可能构造无效概率.

可能不是你想要的双线,但哦,好吧.

为了获得额外的可组合性,您可以通过创建BoundCheck模块而不是"概率"来分解此功能.就像上面一样,除了:

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)
    ...
Run Code Online (Sandbox Code Playgroud)

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

要做到这一点,您可能需要语言扩展{-# LANGUAGE GeneralizedNewtypeDeriving #-}.

  • 概率实际上是一个数字吗?确实,底层表示是,并且您必须对该底层表示进行算术运算以评估概率表达式的结果.但是对概率的实际操作将是(con/dis)连接和反转. (7认同)