#Pattern matching with constants

1 messages · Page 1 of 1 (latest)

manic crystal
#

Hi! I was looking through some code and found this (all type ids are ints)

case type_id {
  _ if type_id == type_ids.end -> ...
  _ if type_id == type_ids.byte -> ...
  _ if type_id == type_ids.short -> ...
  _ if type_id == type_ids.int -> ...
  _ if type_id == type_ids.long -> ...
  ...
  _ -> Error(Nil)
}

and figured it could be improved by matching on type_ids.<name> directly- however, this doesn't work because you cant pattern match on constants

Would it be more gleamy to use a new type and a specific function to match like the following?

// type_ids.gleam
pub type TagID {
  EndTag
  ByteTag
  ShortTag
  IntTag
  LongTag
  ...
}

pub fn to_id(value: Int) -> Result(TagID, Nil) {
  case value {
    0 -> Ok(EndTag)
    1 -> Ok(ByteTag)
    2 -> Ok(ShortTag)
    3 -> Ok(IntTag)
    4 -> Ok(LongTag)
    ...
    _ -> Error(Nil)
  }
}
quaint gull
#

The one with the guards looks good to me

manic crystal
#

thanks!

#

will it ever be possible to match on constants?

quaint gull
#

What do you mean?

manic crystal
#

like

case type_id {
  type_ids.end -> ...
  type_ids.byte -> ...
  type_ids.short -> ...
  type_ids.int -> ...
  type_ids.long -> ...
quaint gull
#

We wouldn’t have a syntax that only works for imported things

#

And we don’t like to have multiple syntaxes for the same thing, this would do exactly the same as the guard example

#

New features have to enable things not previously expressable