Skip to content

Instantly share code, notes, and snippets.

@jadlr
Created May 10, 2017 08:22
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 jadlr/85c5c4f8974ce4e5b1d507867857d7f4 to your computer and use it in GitHub Desktop.
Save jadlr/85c5c4f8974ce4e5b1d507867857d7f4 to your computer and use it in GitHub Desktop.
Slowly relearning Scala syntax
import java.util.NoSuchElementException
import cats._
import cats.implicits._
import scala.annotation.tailrec
object Max extends App {
def maximum[A : Order](list: List[A]): A = list match {
case Nil => throw new NoSuchElementException
case x :: Nil => x
case x :: xs => x max maximum(xs)
}
def maximumTr[A : Order](list: List[A]): A = {
@tailrec
def go(list: List[A], y: A): A = list match {
case Nil => y
case x :: xs => go(xs, x max y)
}
list match {
case Nil => throw new NoSuchElementException
case x :: xs => go(xs, x)
}
}
println(maximum(List(1,5,3,6)))
println(maximumTr(List(1,5,3,6)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment