Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How do I create a function that allows none, one or two Applicatives?

Control.Applicative.optional allows to handle zero or one Applicatives. many & some allow for 0 or more, or 1 or more, respectively. I'd like to create a function that handles zero, one or two, specifically. The signature could be as for many/some, that is

zeroOneOrTwo :: Alternative f => f a -> f [a]

I feel this should be pretty straightforward, but I've been playing around with it for a while and cannot make it work. Any pointers would be greatly appreciated.

like image 720
user3416536 Avatar asked Sep 25 '16 19:09

user3416536


1 Answers

How about this one:

zeroOneOrTwo :: Alternative f => f a -> f [a]
zeroOneOrTwo a = go (2 :: Int)
  where
    go n
      | n > 0 = ((:) <$> a <*> go (n - 1)) <|> pure []
      | otherwise = pure []
like image 193
redneb Avatar answered Sep 26 '22 18:09

redneb