Reputation: 119
I am using haskell to write a Defition of byte in combination with a definition of finite to create an occurrence of a finite byte.
This is what I have so far:
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)
I'm just stuck on this last line:
instance Finite Byte where
elements = undefined
The instructions say to give a Finite instance for the Byte type. Do not use the True and False constructors explicitly in your definition.
(Hint: use the list monad or a list comprehension.)
Please don't change anything other than what's left undefined.
Update
This worked:
instance Finite Byte where
elements = Bits <$> elements <*> elements <*> elements <*> elements <*> elements <*> elements <*> elements <*> elements
Upvotes: 0
Views: 177
Reputation: 476594
You can make use of (<$>) :: Functor f => (a -> b) -> f a -> f b
and (<*>) :: Applicative f => f (a -> b) -> f a -> f b
. To construct a list of all values of Byte
.
For example if you make a data type Nibble
:
data Nibble = Nibble Bool Bool Bool Bool
You can obtain a list of all possible Nibble
s with Nibble <$> [False, True] <*> [False, True] <*> [False, True] <*> [False, True]
. This thus will be [Nibble False False False False, Nibble False False False True, …, Nible True True True True]
.
If you thus make Bool
an instance of Finite
, like @Aplet123 says, then you can make use of elements
to obtain the list of values for Bool
, and then define an instance for Byte
:
instance Finite Bool where
elements = [False, True]
instance Finite Byte where
elements = … -- with Byte, <$>, <*> and elements
where you fill in …
based on the way we can define this for Nibble
.
Upvotes: 2