Is there any fundamental limitations that stops Scala from implementing pattern matching over functions?

后端 未结 4 1813
不思量自难忘°
不思量自难忘° 2021-02-18 17:54

In languages like SML, Erlang and in buch of others we may define functions like this:

fun reverse [] = []
|   reverse x :: xs  = reverse xs @ [x];
4条回答
  •  旧巷少年郎
    2021-02-18 18:19

    In SML, your code snippet is literally just syntactic sugar (a "derived form" in the terminology of the language spec) for

    val rec reverse = fn x =>
        case x of [] => []
                | x::xs  = reverse xs @ [x]
    

    which is very close to the Scala code you show. So, no there is no "fundamental" reason that Scala couldn't provide the same kind of syntax. The main problem is Scala's need for more type annotations, which makes this shorthand syntax far less attractive in general, and probably not worth the while.

    Note also that the specific syntax you suggest would not fly well, because there is no way to distinguish one case-by-case function definition from two overloaded functions syntactically. You probably would need some alternative syntax, similar to SML using "|".

提交回复
热议问题