37 lines
974 B
Scala
37 lines
974 B
Scala
import scala.annotation.tailrec
|
|
|
|
def countTrue(bools: List[Boolean]): Int = {
|
|
bools.foldLeft(0)((n, bool) => if (bool) n + 1 else n)
|
|
}
|
|
|
|
countTrue(List(true, true, false, true, false, false))
|
|
|
|
def remDup[T](list: List[T]): List[T] = {
|
|
list.foldRight(List.empty[T])((elem: T, res: List[T]) => {
|
|
if (res.contains(elem)) res
|
|
else elem::res
|
|
})
|
|
}
|
|
|
|
def remDup2[T](list: List[T]): List[T] = {
|
|
list.foldLeft(List.empty[T])((res: List[T], elem: T) => {
|
|
if (res.contains(elem)) res
|
|
else res :+ elem
|
|
})
|
|
}
|
|
|
|
def remDup3[T](list: List[T]): List[T] = {
|
|
@tailrec
|
|
def helper(list: List[T], distinct: List[T]): List[T] = {
|
|
list match {
|
|
case head::rest if distinct.contains(head) => helper(rest, distinct)
|
|
case head::rest => helper(rest, distinct :+ head)
|
|
case Nil => distinct
|
|
}
|
|
}
|
|
helper(list, List.empty[T])
|
|
}
|
|
|
|
remDup(List(5,3,2,4,3,2,3,3)) // List(5,3,2,4)
|
|
remDup(List("hello", "youpi", "hello", "hello")) // List("hello", "youpi")
|