r/functionalprogramming • u/brett9897 • Feb 08 '23
Question Existing Pattern for Trying Multiple Code Blocks
I might be going about this the wrong way but is there already an existing pattern that I can research that basically does the following.
tryA
if not a then
tryB
if not b then
tryC if not c then
...
else
c
else
b
else
a
Basically I am looking for something that behaves the opposite of Option/Maybe. I want to map over it only if it is None. I could build this pattern myself but I wanted to know if there is already an existing pattern whose name I should know.
4
Upvotes
3
u/[deleted] Feb 08 '23
Pattern? Sure, but it's just a function. In F# such a function is named
Option.orElseWithNot hard to write yourself.
7
u/saucedgarlic Feb 08 '23
This sounds similar to Alternative functors
1
u/it_snow_problem Feb 08 '23 edited Feb 08 '23
Without further narrowing of the problem, there’s not a one right pattern I would suggest. I’d do one thing if the number of trys is potentially arbitrary vs fixed. I’d do one thing if there’s a single definition of “try” or if each of these is a different function or if each is an already realized value.
So one way to do it is to
Enum.findover the list of trys, calling each try until one returns the first truthy value.Also you’re just describing an else if.
“if tryA, return a; else if tryB, return b; else if tryC, return C; …” which could also simplify to “tryA or tryB or tryC or …”. I don’t see the need to nest. Repeatedly checking for “not a” instead of “a” looks like a classic anti pattern.
1
u/[deleted] Feb 08 '23
[removed] — view removed comment