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

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

 

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

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

 

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

三、構造類型的關聯類型的概念與行爲,及與構造類型複合到一塊兒的行爲。函數式編程

構造類型與關聯類型的複合行爲。函數

 

typeclass是上面行爲的描述;this

 

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

 

//list Functor的實現blog

def listFunctor = new Functor[List] {接口

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

 

考慮重點:一、構造類型的行爲;二、關聯類型的行爲。

 

 

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:接口約束;

相關文章
相關標籤/搜索