函式式程式設計筆記 09

2021-09-11 13:40:16 字數 3132 閱讀 5096

scalelist

def

scalalist

(xs: list[double], factor: double): list[double] = xs match

複製**

抽象成map

abstract

class

list[t]

defscalelist

(xs: list[double], factor: double) =

xs map (x => x * factor)

複製**

poselems

def

postelems

(xs: list[int]): list[int] = xs match

複製**

抽象成filter

abstract

class

list[t]

}def

poselems

(xs: list[int]): list[int] =

xs filter (x => x > 0)

複製**

xs filternot p    // xs filter (x => !p(x))

xs partition p // (xs filter p, xs filternot p)

xs takewhile p // 滿足p的最長字首

xs dropwhile p // 不滿足p的最長字首

xs span p // (xs takewhile p, xs dropwhile p)

複製**

練習:寫乙個函式pack,使得

pack(list("a", "a", "a", "b", "c", "c", "a"))

複製**

返回

list(list("a", "a", "a"), list("b"), list("c", "c"), list("a"))

複製**

答案:

def

pack

[t](xs: list[t]): list[list[t]] = xs match

複製**

比如

sum(list(x1, …, xn))        // = 0 + x1 + … + xn

product(list(x1, …, xn)) // = 1 * x1 * … * xn

複製**

sum函式可以這樣寫:

def

sum(xs: list[int]): int = xs match

複製**

list(x1, …, xn) reduceleft op = (…(x1 op x2) op …) op xn

複製**

reduceleft可以簡化上面兩個函式:

def

sum(xs: list[int]) = (0 :: xs) reduceleft (_ + _)

defproduct

(xs: list[int]) = (1 :: xs) reduceleft (_ * _)

複製**

其中每乙個_從左向右都代表乙個新引數。

foldleftreduceleft類似,但它多了乙個累加器,當在空列表上呼叫foldleft時就會返回它。

(list(x1, …, xn) foldleft z)(op) = (…(z op x1) op …) op xn

複製**

所以sumproduct也可以這樣定義:

def

sum(xs: list[int]) = (xs foldleft 0) (_ + _)

defproduct

(xs: list[int]) = (xs foldleft 1) (_ * _)

複製**

foldleftreduceleft可以在list中這樣實現:

abstract

class

list[t]

deffoldleft

[u](z: u)(op: (u, t) => u): u = this

match

}複製**

list(x1, …, x, xn) reduceright op    // x1 op (… (x op xn) …)

(list(x1, …, xn) foldright acc)(op) // x1 op (… (xn op acc) …)

複製**

實現:

def

reduceright

(op: (t, t) => t): t = this

match

deffoldright

[u](z: u)(op: (t, u) => u): u = this

match

複製**

練習:如果把下面函式中的foldright換成foldleft會發生什麼錯誤?

def

concat

[t](xs: list[t], ys: list[t]): list[t] =

(xs foldright ys) (_ :: _)

複製**

答案是型別錯誤。

函式式程式設計筆記

在數學的發展史上,針對category theory出現了一整套函式的運算方法,這個方法被用於程式設計就是現在的函式式程式設計。所以函式式程式設計的本質是數學的運算方法。我們都知道,數學的原始目的是求值。我理解的數學就是 給你一些條件,然後我需要乙個結果,過程是怎樣我是不管的。所以函式式程式設計的目...

RxSwift筆記 函式響應式程式設計

常見程式設計模式 函式式程式設計的乙個特點就是,允許把函式本身作為引數傳入另乙個函式,還允許返回乙個函式。我們可以通過組合不同的函式來得到想要的結果 函式式程式設計是用遞迴做為控制流程的機制 函式程式設計典型例項是高階函式 詳情請參考 阮一峰的日誌 函式式程式設計初探 函式式程式設計特點 維基百科 ...

Scala學習筆記 函式式程式設計

在函式式程式設計中,函式式第一等級的值,就像資料變數的值一樣,你可以從函式中組合形成新函式 如 tan x sin x cos x 可以將函式賦值給變數,也可以將函式作為引數傳遞給其它函式,還可以將函式作為其它函式的返回值。當乙個函式採用其它函式作為變數或返回值時,它被稱為高階函式。deffacto...