DAY 9
0
Software Development

yo, what's up?

## What's type signature?

Java

``````public static int add(int a, int b);
``````

## Hindley-Milner type signature

``````add :: Number -> Number -> Number
``````

## Basic

### Single argument

``````// length :: String -> Number
const length = str => str.length;
``````

`length :: String -> Number` ，將其拆解分析

### Multiple argument

``````// add :: (Number, Number) -> Number
const add = (x, y) => x + y;
``````

ES6 Arrow function

``````(x, y) => x + y
``````

HM type signature

``````(Number, Number) -> Number
``````

### List of values

``````const take = (position) => (arr) => arr.at(position)
``````

``````take :: Number -> [Number] -> Number
``````

### Function (higher-order function)

``````const map = (fn) => (arr) => arr.map(x => fn(x));

map(length, ['hello', 'functional', 'programming'])
``````

``````map :: (String -> Number) -> [String] -> [Number]
``````

## Type Variable

### what's the problem?

``````map(double, [1, 2, 3, 4]) // [1, 4, 9, 16]
map(isEven, [1, 2, 3, 4]) // [false, true, false, true]
``````

``````map :: (Number -> Number) -> [Number] -> [Number]
map :: (Number -> Boolean) -> [Number] -> [Boolean]
``````

### how to solve?

``````map :: (a -> b) -> [a] -> [b]
``````

1. 型別的寫法區分

• 通用的型別用以 小寫 作為開頭，例如 `a`, `b`, `c`,...
• 特定的型別則是用 大寫 作為開頭，例如 `String`, `Number`, `Boolean`...

2. 通用型別在同一個 type signature 不能夠進行複用，除非該通用型別皆指向相同的特定型別

``````map :: (a -> a) -> [a] -> [a]
``````

3. 不同的通用型別可以代表相同的特定型別

``````map(double)([1, 2, 3, 4]) // [1, 4, 9, 16]
``````

## Type Constraints

``````equals :: Setoid => a -> a -> Boolean
``````

## 小結

NEXT: Type class & ADT

## Reference

### 1 則留言

1
Ken Chen
iT邦新手 5 級 ‧ 2021-09-25 17:33:24