Add range match support for comparable values in the IR #63
AttilaMihaly
started this conversation in
Ideas
Replies: 1 comment
-
Here's one potential implementation for the API used in the code above: type RangeMatch a b
= Next RangeType a
| Done b
type RangeType
= Inclusive
| Exclusive
rangeMatch : comparable -> RangeType -> RangeMatch comparable a
rangeMatch subject rangeType =
Next rangeType subject
below : comparable -> (comparable -> a) -> RangeMatch comparable a -> RangeMatch comparable a
below bound f cont =
case cont of
Next rangeType subject ->
case rangeType of
Inclusive ->
if subject <= bound then
Done (f subject)
else
cont
Exclusive ->
if subject < bound then
Done (f subject)
else
cont
Done a ->
Done a
above : (comparable -> a) -> RangeMatch comparable a -> a
above f cont =
case cont of
Next _ subject ->
Done (f subject)
Done a ->
Done a
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The need to map ranges of numeric values to various categories comes up frequently in finance but there is no convenient way to represent those in Morphir. The closes you can get is an if-then-else chain:
While this is somewhat manageable it is not a direct representation of the business problem and it's easy to make mistakes which are difficult to spot. For example this one:
This is very confusing because the ranges are not in a sequential order in the code.
This pattern is so common though that I think it deserves direct language support and I think we can easily add it. To make this possible we just need a simple API in Elm:
There are a few advantages here:
foo
only appears once)Constraints on the structure of the range match will allow us to do more efficient optimizations in our backends and most importantly make it very easy to verify correctness (it simply amounts to checking if the boundaries are ordered correctly).
Beta Was this translation helpful? Give feedback.
All reactions