Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

haskell - function that gets an Int and returns a list

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...