Created
June 19, 2020 01:54
-
-
Save lunaspeed/6a20619baa5f2198ac22485af01e0de1 to your computer and use it in GitHub Desktop.
scala functional
This file contains hidden or 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
def sum(li: List[Int]): Int = { | |
var total = 0 | |
for (i <- li) { | |
total = total + i | |
} | |
total | |
//只能加Int? |
This file contains hidden or 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
trait Append[A] { | |
def add(a: A, b: A): A | |
} | |
def sum[A](l: List[A], abs: Append[A]): A = { | |
//拿第一個當作起始點 | |
var total = l.head | |
for (a <- l.tail) { | |
total = abs.add(total, a) | |
} | |
total | |
} | |
//如果list是空的怎麼辦? |
This file contains hidden or 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
trait Append[A] { | |
def add(a: A, b: A): A | |
def zero(): A //加一個default值 | |
} | |
def sum[A](l: List[A], abs: Append[A]): A = { | |
var total = abs.zero | |
for (a <- l) { | |
total = abs.add(total, a) | |
} | |
total | |
} | |
//我只能在list上面做加總?Map可以嗎?Array可以嗎? |
This file contains hidden or 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
trait Append[A] { | |
def add(a: A, b: A): A | |
def zero(): A //加一個default值 | |
} | |
//整個動作抽象出來叫做fold: 把一堆東西(A)壓縮成一個(A) | |
//F[_] == List[A] | |
//可以為List, Array, Map, Set, 任何合理的東西都可以實作一個 | |
trait Foldable[F[_]] { | |
def fold[A](l: F[A])(M: Append[A]): A | |
} | |
//List的實作 | |
class ListFoldable extends Foldable[List] { | |
def fold[A](l: List[A])(M: Append[A]): A = { | |
var r = M.zero | |
for (a <- l) { | |
r = M.add(r, a) | |
} | |
r | |
} | |
} | |
def sum[F[_]: Foldable, A](l: F[A], abs: Append[A]): A = { | |
Foldable[F].fold(l,abs) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment