Created
May 10, 2017 08:22
-
-
Save jadlr/85c5c4f8974ce4e5b1d507867857d7f4 to your computer and use it in GitHub Desktop.
Slowly relearning Scala syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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