Instantly share code, notes, and snippets.

@passy /Term.kt
Last active Nov 19, 2017

What would you like to do?
sealed class Term
data class Num(val n: Int) : Term()
data class Var(val name: String) : Term()
data class Mul(val l: Term, val r: Term) : Term()
data class Add(val l: Term, val r: Term) : Term()
fun simplify(term: Term): Term =
when (term) {
Mul(Num(0), x) -> Num(0),
Mul(Num(1), x) -> x,
_ -> term

This comment has been minimized.

Copy link

elizarov commented Nov 19, 2017

In modern Kotlin I would have written this simplify function like this:

fun simplify(term: Term): Term = when {
  term is Mul && term.l == Num(0) -> Num(0),
  term is Mul && term.l == Num(1) -> x,
  else -> term

This is, no question, more verbose than the syntax with pattern matching. Yet, pattern matching is a heavy feature to carry around just for rare cases like that.

In a dynamic language, like Erlang, for example, pattern-matching is the cornerstone of everything, helping programmer to make sense of the data structures that theirs functions are processing, because there are no static types there to guide them. In Kotlin, unlike Erlang, full-blown pattern-matching would be a fringe feature, used so rarely, that few developers would even know or understand its syntax.

IMHO, this kind of syntax has to be useful beyond when expressions to justify its weight.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment