1

I have pattern matching in Scala with a long case of which I use a large part. Can I name the part of the case so I don't have to rewrite the whole expression?

Example:

x match {
    case (("def", symPos) :: defRest, defPos) :: rest =>
        val (defs, others) = split(rest)
        ((("def", symPos) :: defRest, defPos) :: defs, others)
    // …
}

The pattern (("def", symPos) :: defRest, defPos) is just to detect a certain structure in the data; I don't need to manipulate its internals. If I could refer to the whole thing, the code would be shorter and clearer.

In Haskell, I could write it this way:

case x of
    def@(("def", _) : _, _) : rest ->
        let (defs, others) = split rest
        in (def : defs, others)
    -- …

Here, I name the greater pattern def, which allows me to omit the names of its internals and use just the name to put it to a list. Can I do something like that in Scala? I didn't find anything.

matj1
  • 158
  • 1
  • 11
  • It's not clear for me what is the structure that you are trying to pattern match. It looks like is a List of Tuples, but I'm not sure. Could you add the definition of the classes that you want to match? – Gastón Schabas Jun 26 '23 at 12:43
  • 2
    Scala supports similar syntax https://stackoverflow.com/q/2359014/29470 – Tim Moore Jun 26 '23 at 12:49
  • Almost identical, it's called a "pattern alias" in Scala. – AminMal Jun 26 '23 at 13:53
  • @TimMoore Why can't I find anything about it in the documentation? – matj1 Jun 26 '23 at 15:14
  • @GastónSchabas The example is simplified. The original looks for top-level definitions (starting with “def”) in an abstract syntax tree. I replaced case classes with tuples to make the example simpler. – matj1 Jun 26 '23 at 15:23
  • I haven't coded in haskell for a while, not sure what exactly you are looking for. You have the [specs for pattern matching in scala 2.13](https://www.scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html) and [what changes were introduced in scala 3 in pattern matching](https://docs.scala-lang.org/scala3/reference/changed-features/pattern-matching.html). If you give more details about what are those lines in haskell means, I can try to help you to find which is the pattern that scala offers for that if there is one that match with your needs – Gastón Schabas Jun 26 '23 at 16:54
  • @matj1 I don’t know. I agree that it’s hard to find. It seems like an oversight. – Tim Moore Jun 26 '23 at 22:16

0 Answers0