Record pattern matching

Could not find a way to decompose custom type in function parameter definition when matching record structrure. For example:

type Model = Model Int
x (Model a as m) = a   -- ok
type alias Rec = {a: Int, b: Model}
y {a, b} = a + (\(Model x) -> x) b --ok

y {a, Model x as b} = a + x -- compiler error

Should that be possible or there is some other way to do something like this?

As far as I know, there is no way to have a nested pattern in a field of a record. as is really used if you don’t want to reconstruct the thing you deconstructed in the pattern, so you can just use m in your x function above if you find yourself needing to write Model a.

In my case it would be handy if I could write like this, otherwise I had to write something like first example of function y in order to pass parameter of Rec type to it. Anyway thanks for the answer!

1 Like

You could also do something like this

y { a, b } =
    let
        (Model x) =
            b
    in
    a + x

Then you don’t have to use an anonymous function.

If you use a custom type to wrap a regular type you should provide and an unwrap function.

type Model = Model Int
unwrap (Model value) = value 

type alias Rec = {a: Int, b: Model}
y {a, b} = a +  (unwrap b) 

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.