Created
March 9, 2016 17:50
-
-
Save hussachai/ad19a906e078d4c58465 to your computer and use it in GitHub Desktop.
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 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