Day 10 - Algebraic structure

yo, what's up

本章要来介绍 FP 的重要观念,Algebraic structure!

What's Algebraic structure?

In mathematics, and more specifically in abstract algebra, an algebraic structure on a set A (called carrier set or underlying set) is a collection of finitary operations on A ; the set A with this structure is also called an algebra. - James Sinclair

而简单来说,可以把它想像成一组元素的集合(又称 Object),其包含一些操作(operation)在里面,而这种结构又称 Algebra.

注: 这里的 Object 并不是 JS 的 Object,可以先把它想像成一个 Container 里面封装的一些元素.

像是 Semigroup, Functor, Applicative 跟 Monad 这些陌生的名词,其实都是基於此一概念,它们都属於 Algebraic structure.

而未来也会介绍一系列的 Monad 像是处理 Side Effect 的 IO Monad, 处理错误情境的 Either Monad 等等,其背後都有相同的 method 名称,像是 .map, .ap, 又或是 .chain。 这并不是巧合,每个 method 背後都遵循同典范 (pattern),没错,就是 Algebraic structure.

Algebraic structure in JavaScript

当初读者在研究 FP 的时候,曾经怀疑会想为何一定要遵循同典范,内心就想为何不能(又或是没有套件开发者)把 method 像是 map, 将它的名称改成 then 之类的,为何不能有属於自己的 style!!!!

以 JavaScript 为例,其实有一个让开发者参照的规格书,就是 fantasy-land spec,内容并没有告诉套件开发者该如何实作,只有列出规范,例如 method 的名称,以及它该符合哪些特性(law)。

下面就是 fantasy-land 对於列出 Algebraic structure 的关联图,并对其进行规范,并且套件开发者等就会有共识地去遵从这些规范。

fantasy-land

Example

举例 Setoid 这个 Algebraic structure 为例,在 fantasy-land spec 中,其规范了 method 跟 其必须遵循某些特性

method (HM Type signature)

顺带一提,前一篇提到的 Setoid 在 fantasyland spec 并不是

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

而多了新的符号 ~> 在内

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

~> 的意思就是 a 必须要有 equal 这个 method,而 ~> 右方才为 equal 的 signature.

整句就是若 a 是 Setoid 且有 equals 这个 method 在内, 则 a -> a -> Boolean 成立。

law

并且如果 a 为 Setoid 必须符合哪些三项特性(law)

1. reflexivity:

a.equals(a) === true

2. symmetry

a.equals(b) === b.equals(a)

3. transitivity

a.equals(b) && b.equals(c) === a.equals(c)

implement

现在来实作出一个比较是否为两值是否相等的 Setoid 吧!!

import * as R from 'ramda';

const Setoid = (val) => ({
    val, 
    equals: o => R.equals(val, o.val),
    inspect: () => `Setoid(${val})`
})

Setoid('Functional Progamming').equals(Setoid('Functional Progamming')) // true

Setoid('Functional Progamming').equals(Setoid('Object Oriented Progamming')) // false

而这里使用 ramda 所提供的函式 equals, 虽然简单,但这是我们实作的第一个 Algebraic structure!

读者们可以验证一下是否符合 fantasy-land 的规范!

小结

富间了,富间了,决定将 Type class 跟 ADT 的概念一到下一章,这章就先简单介绍 Algebraic structure 相关概念!

而 TS 对於其定义更严谨(理论上是更贴近真正的概念),此次范例只是简单 demo Algebraic structure 的概念,范例仅作教学用途,不适合用在 Production 上。可以使用 fp-ts 的 Setoid

欢迎来到 Functional Programming 的世界!

Reference

  1. fp-ts equals
  2. Algebraic structure

<<:  30天学会Python: Day 9- 程序码也能取名字

>>:  Day11 Sideproject(作品集) from 0 to 1 - docker化前端篇

[DAY 18] _UART传输

这是算是大家最常见串列通讯,他原理较简单方便,现在韧体工程师在除错或为简单验证资料,大家知道TX、R...

GNU Compiler Collection

GCC 是 GNU Compiler Collection 的简称,GCC 原本称为 GNU C ...

Day#19 Firebase database 101

前言 已经快要到三分之二了,标题名称取到山穷水尽 Firebase Database Auth St...

Day 27 Redux 接入 component

第 27 天 ! 昨天我们把 redux 给接入到我们的专案上, 那今天试着把 store 的 st...

Day-26 吹奏创意的一曲、红透半边天的 Switch

面对效能强大的 PS4 与 XB1、任天堂这次依然不跟对手比效能、以创意来对决、而且还因为怕被对手复...