3

I have a function defined

maybeToList :: (a -> Maybe a) -> a -> [a] maybeToList f x = x : maybe [] (maybeToList f) (f x) 

This function seems so obvious that I can't believe it is not standard. Is it defined in some module (I already checked Data.Maybe)?

1
  • 1
    maybeToList is not the best name, considering that there is already a function with that name in Data.Maybe, namely maybeToList = maybe [] (:[]). unfoldStream or something maybe? Commented Dec 6, 2012 at 6:33

1 Answer 1

6

Your function isn't in the standard libraries because it's a specialized form of one that is:

unfoldr :: (b -> Maybe (a, b)) -> b -> [a] unfoldr f b = case f b of Just (a,new_b) -> a : unfoldr f new_b Nothing -> [] 

That said, the case where the list elements are the same as the sequence of seed values is common, and it's clumsy to write in terms of just unfoldr and other standard functions, so I'm not sure why it's not in the standard libraries as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, though I think it might be clearer to define a function than to write unfoldr (join (,) . foo) :p.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.