It seems I'm using over and over a pattern that I would like to abstract as a function. The idea behind the pattern is that maybe I have something and if not I can try to produce it. Here is some OCaml code for the function I'm interested in naming, but the problem isn't OCaml specific. I looked for a Haskell precedent but I haven't seen such a function in the Data.Maybe module and hoogle didn't help: http://www.haskell.org/hoogle/?hoogle=Maybe+b+-%3E+%28a+-%3E+Maybe+b%29+-%3E+a+-%3E+Maybe+b.
let my_function a f arg = match a with
| None -> f arg
| Some _ -> a
This is almost like having a default potential value, but it avoid the need for generating the default if we have a value already.
Edit:
The reason I need this type is that I have a combinatorial problem to solve and a set of heuristics to solve it (say h1 and h2). h1 is faster than h2. None of these heuristics is guaranteed to find a solution, though. So I chain them and try them in order. Something like
match my_function (h1 problem) h2 problem with
| None -> "bad luck"
| Some solution -> "hurray"
Sounds like Alternative
pattern:
a <|> f arg
In Haskell notation, your function is essentially
func :: Maybe a -> (b -> Maybe a) -> b -> Maybe a
func a f arg = case a of
Nothing -> f arg
Just _ -> a
Notice that you only ever use the inputs f
and arg
in the combination f arg
, so you can simplify to
helper :: Maybe a -> Maybe a -> Maybe a
helper a b = case a of
Nothing -> b
_ -> a
func a f arg = helper a (f arg)
That is, your helper produces a
if it has a value, otherwise it produces b
. But you can write that in terms of maybe
from Data.Maybe
helper :: Maybe a -> Maybe a -> Maybe a
helper a b = maybe b id a
func a f arg = helper a (f arg)
and then if you wanted you could inline the definition of helper
func a f arg = maybe (f arg) id a
So I don't think you have a pattern that already exists, but it's a simple variation on the maybe
function, that does already exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With