applicative - In Haskell, is there an abstraction for the <?>-operator? -
i found myself writing code:
import control.applicative ((<|>)) x = ma <|> mb <?> c (<?>) :: maybe -> -> x <?> _ = x nothing <?> y = y
where ma :: maybe a
, mb :: maybe a
, c :: a
, , x :: a
. basically, code says: pick first alternative not empty
, default c
. can call "reverse maybe monad" analogy <?>
pure
.
equivalently, have written
just x = ma <|> mb <|> pure c,
but feel uncomfortable irrefutable pattern. or, of course,
x = frommaybe c (ma <|> mb)
because frommaybe === flip <?>
.
the <?>
operator inspired parsec. suspicious when find myself defining utility functions that, couldn't find defaulting behavior anywhere.
apparently alternative
, applicative
not powerful enough.
did miss type-class?
i think it's idea leave things @ (<?>) = flip frommaybe
.
if you'd generalize though, foldable
seems simplest class notion of emptiness:
(<?>) :: foldable t => t -> -> ta <?> = foldr const ta
this returns a
if ta
empty or else first element of ta
. examples:
just 0 <?> 10 == 0 nothing <?> 0 == 0 [] <?> 10 == 10
Comments
Post a Comment