pattern matching on a field within a record

135 views
Skip to first unread message

Martin DeMello

unread,
Sep 22, 2016, 9:50:19 PM9/22/16
to elm-d...@googlegroups.com
If I have the following code:

type Cell = Empty | Letter String

type alias Square =
  { cell : Cell
  , num : Int
  } 

and c : Maybe Square,

can I do the following in a single match?
 
  case c of
    Just { cell } ->
      case cell of
        Letter s -> s
        _ -> ""
    _ -> ""

that is, i conceptually want

  case c of
    Just { cell = Letter s } -> s
    _ -> ""

martin

Max Goldstein

unread,
Sep 22, 2016, 11:55:07 PM9/22/16
to Elm Discuss
I don't think there's a more compact way to do that, no.

Simon

unread,
Sep 23, 2016, 3:04:29 PM9/23/16
to Elm Discuss
This should work
 
 case c of
    Just (Letter s) ->
      s
    _ -> ""

Martin DeMello

unread,
Sep 24, 2016, 4:44:50 PM9/24/16
to elm-d...@googlegroups.com
Don't think that will work because c is of type Maybe Square, not Maybe Cell.

One further question - if I define

let null_square = { cell = Empty, num = 0 }

let get_square maybe_square =
  case maybe_cell of
    Nothing: null_square
    Just s : s

let get_letter maybe_square =
  case maybe_square of
    { Letter s } -> s
    _ -> ""

would that be introducing an inefficient creation of a null_square every time I call get_letter or is it just a cheap reference?

martin

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nick H

unread,
Sep 25, 2016, 12:11:04 AM9/25/16
to elm-d...@googlegroups.com
Re: your initial post... you could rewrite the code as

case Maybe.map .cell c of
  Just (Letter s) ->
    s
  _ ->
    ""

Don't know if that's any easier to read, though.

Regarding null_square: If you want to make sure that null_square is passed by reference, you can define it as a top-level value. (That said, the record is so small, I doubt it would make a noticeable performance difference, unless you're planning on making a gazillion of them.)
 

Martin DeMello

unread,
Sep 25, 2016, 2:58:24 AM9/25/16
to elm-d...@googlegroups.com
On Sat, Sep 24, 2016 at 9:11 PM, Nick H <falling...@gmail.com> wrote:

Regarding null_square: If you want to make sure that null_square is passed by reference, you can define it as a top-level value. (That said, the record is so small, I doubt it would make a noticeable performance difference, unless you're planning on making a gazillion of them.)

That's what I ended up doing, and the code was pretty nice with it.

martin 
Reply all
Reply to author
Forward
0 new messages