问题
I have an exercise in Haskell where I need to create various types.The first type is called Finite which is defined like this:
type Finite a = [a]
and then I need to return a singleton which is defined like this
singleF :: a -> Finite a
so I implemented it like so:
single n = [n]
Then later I create another type
type Enumeration a = Int -> Finite a
then I need to reimplement the singleton function
singleE :: a -> Enumeration a
In my understanding the type Enumeration is a synonym for a function from an Int to a list of type a, but I can't understand how exactly I can implement that.
From the exercise (the previous type 'Finite' is also referred to as a 'bucket'): An enumeration is an infinite sequence of finite buckets, indexed by natural numbers.
And the function single : I suggest for simplicity that you put the sole item in bucket 0, So I'm thinking that the int is the index of the bucket in the enumeration
回答1:
Off the top of my head:
singleE :: a -> Enumeration a
singleE a 0 = singleF a
singleE _ _ = []
main :: IO ()
main = do
let s=singleE 'a'
print $ s 0
print $ s 5
Gives
"a"
""
singleE gives you a function that takes an Int and returns a Finite. If you pass 0, you get a Finite with the single element, otherwise an empty one.
来源:https://stackoverflow.com/questions/35684605/function-that-gets-an-int-and-returns-a-list