Skip to content

Instantly share code, notes, and snippets.

@passy
Last active November 19, 2017 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passy/6b1c0ab33135b8d0715e47e3d21a57c9 to your computer and use it in GitHub Desktop.
Save passy/6b1c0ab33135b8d0715e47e3d21a57c9 to your computer and use it in GitHub Desktop.
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
}
@elizarov
Copy link

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