function that gets an Int and returns a list

青春壹個敷衍的年華 提交于 2019-12-13 10:58:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!