如何解决Haskell有限字节
我正在使用haskell结合定义finite来编写字节定义,以创建有限字节的出现。
这是我到目前为止所拥有的:
module Foldables where
import Prelude hiding (Applicative(..),any,concat)
import Data.Foldable
import Data.Semigroup
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Map.Append (AppendMap(..))
import Data.List (intersperse)
import Data.Maybe (maybe)
import Data.Monoid (Any(..),Sum(..))
import GHC.Generics (Generic)
class Finite (a :: *) where
-- exists n. length elements == n
-- forall x. elem x elements == True
elements :: [a]
instance Finite Bool where
elements = [True,False]
-- The type "Either a b" is finite when both "a" and "b" are finite.
instance (Finite a,Finite b) => Finite (Either a b) where
elements = fmap Left elements ++ fmap Right elements
-- Similarly,the type "(a,b)" is finite when both "a" and "b" are finite.
instance (Finite a,Finite b) => Finite (a,b) where
elements = allPairs elements elements
data Byte = Bits Bool Bool Bool Bool Bool Bool Bool Bool
deriving (Generic,Eq,Show)
我只是停留在最后一行:
instance Finite Byte where
elements = undefined
说明说要为Byte类型提供一个有限实例。 不要在定义中明确使用True和False构造函数。
(提示:使用列表单子或列表理解。)
除了未定义的内容外,请勿进行其他更改。
更新
这有效:
instance Finite Byte where
elements = Bits <$> elements <*> elements <*> elements <*> elements <*> elements <*> elements <*> elements <*> elements
解决方法
您可以使用(<$>) :: Functor f => (a -> b) -> f a -> f b
和(<*>) :: Applicative f => f (a -> b) -> f a -> f b
。构造Byte
的所有值的列表。
例如,如果您输入数据类型Nibble
:
data Nibble = Nibble Bool Bool Bool Bool
您可以使用Nibble
获取所有可能的Nibble <$> [False,True] <*> [False,True]
的列表。因此,它将为[Nibble False False False False,Nibble False False False True,…,Nible True True True True]
。
如果这样将Bool
设为Finite
的实例,例如@Aplet123 says,则可以使用elements
来获取{{1}的值的列表},然后为Bool
定义一个实例:
Byte
根据我们为instance Finite Bool where
elements = [False,True]
instance Finite Byte where
elements = … -- with Byte,<$>,<*> and elements
定义的方式填写…
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。