Is there a standard name for the following function?

I seem to be using over and over a pattern that I would like to abstract as a function. The idea of ​​the template is that maybe I have something, and if not, I can try to create it. Here is what OCaml code is for the function I'm interested in, but the problem is not in OCaml. I looked for a Haskell use case, but I did not see such a function in the Data.Maybe module, and hoogle did not 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 almost looks like a potential default value, but it avoids the need to generate a default value if we already have a value.

Edit:

The reason I need this type is because I have a combinatorial problem to solve and a set of heuristics to solve it (say, h1 and h2). h1 is faster than h2. However, none of these heuristics will find a solution. Therefore, I cling to them and try in order. Sort of

match my_function (h1 problem) h2 problem with
| None -> "bad luck"
| Some solution -> "hurray"
+4
source share
4 answers

Sounds like Alternativepattern:

a <|> f arg

+10
source

What about:

fromMaybe (f arg) a

See: http://www.haskell.org/hoogle/?hoogle=fromMaybe

In addition, Haskell f arghas a chance to calculate when it ais Nothingdue to the fact that Haskell is lazy, unlike OCaml.

+3
source

Haskell

func :: Maybe a -> (b -> Maybe a) -> b -> Maybe a
func a f arg = case a of
  Nothing -> f arg
  Just _  -> a

, f arg f arg,

helper :: Maybe a -> Maybe a -> Maybe a
helper a b = case a of
  Nothing -> b
  _       -> a

func a f arg = helper a (f arg)

, a, , b. maybe Data.Maybe

helper :: Maybe a -> Maybe a -> Maybe a
helper a b = maybe b id a

func a f arg = helper a (f arg)

, ,

func a f arg = maybe (f arg) id a

, , , maybe, .

+3

, , , - ( OCaml Core):

let heuristics = [lazy(h0 "problem"); lazy(h1 "problem"); lazy(h2 "problem")];;
let result = List.find heuristics (fun z -> Option.is_some (Lazy.force z));;

, , .

+1

All Articles