DAY 14
0
Software Development

## Introduction

Type Signature

``````f:: a -> b
g:: c -> d
``````

`safe` 這個函式是會傳一個 Maybe Monad 出來，但要怎麼將包在 Maybe 裡面的 `a` (`Maybe a`) 跟 `toUpper` 這個純函式進行 compose?

``````safe :: (a -> Boolean) -> a -> Maybe a
toUpper :: String -> String
``````

Maybe Monad 可以先想成是專門處理該運算可能會沒有值的情境，這在之後的文章回有更詳細的說明

## Identity

Construction

``````Identity :: a -> Identity a
``````

Implementation

``````const Identity = val => ({
val,
inspect: () => `Identity(\${val})`
})
``````

``````Identity.of = x => Identity(x);
``````

``````Identity.of(1) // Identity(1)
``````

### 為什麼需要 Functor ?

``````const add2 = x => x + 2;

add2(1) // 3
``````

``````add2(Identity.of(1)) // [object Object]2
``````

``````Identity.of(1).map(add2) // Identity(3)
``````

### 什麼是 Functor?

#### Definition of Functor

• `map` method
• 必須符合兩種特性 (`identity` & `composition`)

Type Signature

``````map :: Functor f => f a ~> (a -> b) -> f b
``````

Law

• Identity: `u.map(x => x) === u`
• Composition: `u.map(f).map(g) === u.map(x => g(f(x)))`

``````const Identity = val => ({
val,
map: f => {
const result = f(val); // 將函式套用在val上
return Identity(result);//  將結果包覆回 Identity
}
})
``````

``````const Identity = val => ({
val,
map: f => Identity(f(val)),
inspect: () => `Identity(\${val})`
})
``````

``````Identity.of(1).map(x => x) === Identity.of(1)

Identity.of(1).map(add2).map(add3) === Identity.of(1).map(x => add3(add2(x))))
``````

### 小結

NEXT: Contravariant & Applicative

### 1 則留言

1

iT邦新手 5 級 ‧ 2021-10-24 13:04:03

Functor 的解釋