Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...