对于一个项目,我创建了一个基于Int的类型,只要程序试图使用超出限制的值(在我的情况下为[0..127])就会抛出错误.下面的代码执行此操作,它适用于我.
是否有可能在Haskell中创建第二个有界类型(例如[0..255])而不重复此代码?
谢谢你的回答
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Minitel.Type.MNatural (MNat, mnat, fromMNat) where
-- | The MNat type. The constructor is hidden.
newtype MNat = MakeMNat Int deriving (Real, Eq, Ord, Show)
-- | MNat is a bounded type
instance Bounded MNat where
minBound = MakeMNat 0
maxBound = MakeMNat 127
-- | Converts an Int into an MNat
mnat :: Int -> MNat
mnat x | loLimit <= x && x <= hiLimit = MakeMNat x
| otherwise = …Run Code Online (Sandbox Code Playgroud)