Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does there exist a standard name for the following function?

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"
like image 754
Abdallah Avatar asked Dec 02 '22 21:12

Abdallah


2 Answers

Sounds like Alternative pattern:

a <|> f arg

like image 146
Ankur Avatar answered Feb 01 '23 23:02

Ankur


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.

like image 40
Chris Taylor Avatar answered Feb 01 '23 23:02

Chris Taylor