1. 程式人生 > >函數式編程的類型系統:typeclass--Functor的解釋

函數式編程的類型系統:typeclass--Functor的解釋

orien list use sed 我想 func clas tor learn

函數式編程的類型系統:typeclass

Typeclass是帶有關聯構造類型的抽象接口,抽象接口的行為用於約束構造類型。

構造類型實現了抽象接口的行為約束,就稱這個實現為這個構造類型的函子。

要素:1、關聯的構造類型;2、建立在這個構造類型上的的約束。

3、構造類型的關聯類型的概念與行為,及與構造類型復合到一起的行為。

構造類型與關聯類型的復合行為。

typeclass是上面行為的描述;

結構:typeclass->構造類型(添加約束)->關聯類型(具體類型)。

//list Functor的實現

def listFunctor = new Functor[List] {

def map[A, B](a: List[A])(f: (A) => B) = a.map(f)

考慮重點:1、構造類型的行為;2、關聯類型的行為。

A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they’re not. You can think of them kind of as Java interfaces, only better.

trait Functor[F[_]] {

def map[A, B](a: F[A])(f: A => B): F[B]

}

F[_]:關聯構造類型;

關於FunctorApplicativeMonad的概念,其實各用一句話就可以概括:

  1. 一個Functor就是一種實現了Functor typeclass的數據類型;
  2. 一個Applicative就是一種實現了Applicative typeclass的數據類型;
  3. 一個Monad就是一種實現了Monad typeclass的數據類型。

勘誤:這裏的數據類型應該是構造類型;

當然,你可能會問那什麽是typeclass呢?我想當你在看到實現二字的時候,就應該已經猜到了:

A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they’re not. You can think of them kind of as Java interfaces, only better.

https://www.cnblogs.com/feng9exe/p/8626102.html

Functor的代碼表示

trait Functor[F[_]] {

def map[A, B](a: F[A])(f: A => B): F[B]

}

//list Functor的實現

def listFunctor = new Functor[List] {

def map[A, B](a: List[A])(f: (A) => B) = a.map(f)

}

https://www.cnblogs.com/feng9exe/p/9700779.html

Functor 定義如下:

class Functor f where

fmap :: (a -> b) -> f a -> f b

由 f a 和 f b 我們可知,f 不是類型,而是類型構造器(type constructor),即 f 應接受另一類型作為參數並返回一個具體的類型(更精準的表達則是 f 的 kind 必須是 * -> *)。

https://www.cnblogs.com/feng9exe/p/9152447.html

swift

/// A type that has reactive extensions.

public protocol ReactiveCompatible {

/// Extended type

associatedtype CompatibleType

/// Reactive extensions.

var rx: Reactive<CompatibleType> { get set }

}

extension ReactiveCompatible {

/// Reactive extensions.

public var rx: Reactive<Self> {

get {

return Reactive(self)

}

set {

// this enables using Reactive to "mutate" base object

}

}

}

Reactive<CompatibleType> :構造類型;

rx:接口約束;

函數式編程的類型系統:typeclass--Functor的解釋