Skip to content

Instantly share code, notes, and snippets.

@hussachai
Created March 9, 2016 17:50
Show Gist options
  • Save hussachai/ad19a906e078d4c58465 to your computer and use it in GitHub Desktop.
Save hussachai/ad19a906e078d4c58465 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
import java.io.File
object FirstHomework extends App {
//homework sum 1 to n using recursion
def sumN(n: Int) = {
@tailrec
def sum(c: Int, acc: Int): Int = {
if(c == 0) acc
else sum(c - 1, c + acc)
}
sum(n, 0)
}
def listFiles(src: File): Array[File] = {
val these = src.listFiles()
these.filter(_.isFile()) ++ these.filter(_.isDirectory()).flatMap(listFiles)
}
def listFiles2(src: File) = {
@tailrec
def go(current: List[File], result: List[File]): List[File] = current match {
case head::tail =>
if(head.isFile()) go(tail, result:+head)
else go(tail ++ head.listFiles(), result)
case _ => result
}
go(src::Nil, Nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment