fp-ts Array 模块全解析:用函数式方式驾驭 TypeScript 数组

原创2026-09-22 19:49:551,867 阅读
文章标签:开发工具

fp-ts Array 模块全解析:用函数式方式驾驭 TypeScript 数组

导读

Array 是 fp-ts 中面向 TypeScript 原生 Array<T> 类型的核心模块,它以 monadic(单子)接口包裹数组,让数组具备 map、flatMap、filter、traverse、sequence 等纯函数式能力,且默认不可变、安全(不抛异常、以 Option 表达越界)。本文以 docs/modules/Array.ts.md 为骨架,结合 src/Array.ts 源码与 test/Array.ts 测试,系统讲解构造、转换、过滤、折叠、遍历、实例派生、模式匹配与各类工具函数,帮助读者掌握一套可复制、可运行的数组函数式编程方案。


一、模块定位:数组的单子接口

Array 模块自 v2.0.0 起随 fp-ts 提供,其核心定位(摘自文档概述):

The Array module provides tools for working with TypeScript's Array<T> type in a functional way. In functional jargon, this module provides a monadic interface over TypeScript's Array<T>.

这意味着:

  • 不引入新数据结构:操作对象就是原生 Array<T>,与现有代码无缝互操作;
  • 单子语义:of(单元素数组)与 flatMap(逐元素映射并拼接结果)构成 Monad,数组因此成为一种“非确定性/多结果”计算上下文;
  • 以模块级函数为主:绝大多数函数采用 data-last 柯里化签名,天然适配 pipe 组合。

模块通过类型级别的 URI 常量('Array')参与 fp-ts 的 HKT(高阶类型)体系,从而能够注册 Functor、Monad、Traversable 等实例(见 src/Array.ts 与 docs/guides/HKT.md)。

// 类型级别的标记
export declare const URI: 'Array'
export type URI = typeof URI

二、构造器(constructors):如何造出数组

makeBy —— 按函数生成

返回长度为 n 的数组,第 i 个元素为 f(i)。n 会被归一化为非负整数(负数得到 [],小数向下取整)。

import { makeBy } from 'fp-ts/Array'

const double = (i: number): number => i * 2
assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8])
assert.deepStrictEqual(makeBy(-3, double), [])
assert.deepStrictEqual(makeBy(4.32164, double), [0, 2, 4, 6])

从源码看,其实现正是“非正即空,否则委托给 NonEmptyArray.makeBy”:

// src/Array.ts
export const makeBy = <A>(n: number, f: (i: number) => A): Array<A> => (n <= 0 ? [] : NEA.makeBy(f)(n))

of —— 单点注入

给定一个元素,构造只含该元素的数组。这是构建 Monad 的 pure 操作:

import { of } from 'fp-ts/Array'
assert.deepStrictEqual(of('a'), ['a'])

replicate —— 重复值

创建把同一个值重复 n 次的数组,同样做非负整数归一化:

import { replicate } from 'fp-ts/Array'
assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a'])
assert.deepStrictEqual(replicate(-3, 'a'), [])
assert.deepStrictEqual(replicate(2.985647, 'a'), ['a', 'a'])

源码中 replicate 直接复用 makeBy:export const replicate = <A>(n: number, a: A): Array<A> => makeBy(n, () => a)。


三、转换(conversions):从 Either / Option 进入数组

  • fromEither(v2.11.0):Right 内容成为单元素数组,Left 则得到空数组;
  • fromOption(v2.11.0):Some 内容成为单元素数组,None 得到空数组。

两者都适合与 pipe 配合,把“可有可无”或“可能失败”的值降级为可继续遍历的数组:

import { fromEither, fromOption } from 'fp-ts/Array'
import { either, option } from 'fp-ts'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(pipe(either.right('r'), fromEither), ['r'])
assert.deepStrictEqual(pipe(either.left('l'), fromEither), [])
assert.deepStrictEqual(pipe(option.some('a'), fromOption), ['a'])
assert.deepStrictEqual(pipe(option.none, fromOption), [])

提升函数(lifting)

  • fromEitherK(v2.11.0):把 (...a) => Either<E, B> 提升为 (...a) => B[];
  • fromOptionK(v2.11.0):把 (...a) => Option<B> 提升为 (...a) => B[];
  • fromPredicate(v2.11.0):满足谓词则生成单元素数组,否则空数组,支持 Refinement 版本的类型收窄:
import { fromPredicate } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'
import { isString } from 'fp-ts/string'

assert.deepStrictEqual(pipe('a', fromPredicate(isString)), ['a'])
assert.deepStrictEqual(pipe(7, fromPredicate(isString)), [])
assert.deepStrictEqual(pipe(7, fromPredicate((x) => x > 0)), [7])
assert.deepStrictEqual(pipe(-3, fromPredicate((x) => x > 0)), [])

四、do notation:声明式的链式组合

模块提供完整的 do 记法工具(与 docs/guides/do-notation.md 一致),用于在数组上下文中逐步累积“结构体”:

函数 版本 作用
Do v2.9.0 空记录数组 {}[],链式起点
bindTo v2.8.0 把当前值绑定到指定字段名
bind v2.8.0 基于已有记录计算新的数组并展开绑定
apS v2.8.0 并行地把另一数组结果合并进记录
let v2.13.0 用纯函数计算并新增字段(不产生新数组分支)
guard v2.11.0 条件过滤:true 得 [{}],false 得 []

典型用法——笛卡尔积式的记录构建:

import * as A from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

const result = pipe(
  A.Do,
  A.bind('x', () => [1, 2]),
  A.bind('y', () => ['a', 'b']),
  A.let('label', ({ x, y }) => `${x}${y}`)
)
// [{ x: 1, y: 'a', label: '1a' }, { x: 1, y: 'b', label: '1b' },
//  { x: 2, y: 'a', label: '2a' }, { x: 2, y: 'b', label: '2b' }]

bind 的签名反映了“每个元素都可能扩展出多个结果”的数组单子语义:

export declare const bind: <N, A, B>(
  name: Exclude<N, keyof A>,
  f: (a: A) => B[]
) => (ma: A[]) => { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }[]

五、错误处理:alt 与 altW

  • alt:Semigroup 之于类型构造子的推广;对数组而言即拼接(惰性求值,that 为 LazyArg):
import * as A from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(pipe([1, 2, 3], A.alt(() => [4, 5])), [1, 2, 3, 4, 5])
  • altW(v2.9.0):W 表示 Widening(类型拓宽),允许两个分支类型不同并合并:
assert.deepStrictEqual(pipe([1, 2, 3], A.altW(() => ['a', 'b'])), [1, 2, 3, 'a', 'b'])
// 返回类型为 (number | string)[]

六、过滤家族(filtering):保留、压缩与分拣

compact / filterMap

  • compact:压缩 Option<A>[],丢弃 None、保留 Some 内值;
  • filterMap:先映射为 Option 再压缩,一步完成“映射 + 过滤”:
import { compact, filterMap } from 'fp-ts/Array'
import { option } from 'fp-ts'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(compact([option.some('a'), option.none, option.some('b')]), ['a', 'b'])

const f = (s: string) => (s.length === 1 ? option.some(s.toUpperCase()) : option.none)
assert.deepStrictEqual(pipe(['a', 'no', 'neither', 'b'], filterMap(f)), ['A', 'B'])

filter 与 filterWithIndex

filter 同时支持 Refinement(类型收窄)与 Predicate(布尔判断)两个重载:

import { filter } from 'fp-ts/Array'
import { isString } from 'fp-ts/string'

assert.deepStrictEqual(filter(isString)(['a', 1, {}, 'b', 5]), ['a', 'b'])
assert.deepStrictEqual(filter((x: number) => x > 0)([-3, 1, -2, 5]), [1, 5])

filterWithIndex 额外传入索引:filterWithIndex((index, x) => x > 0 && index <= 2)([-3, 1, -2, 5]) 得 [1]。filterMapWithIndex 同理。

partition / partitionMap / separate

  • partition:按谓词分成 { left, right } 两组(返回 Separated<A[], B[]>);
  • partitionMap:映射函数返回 Either<B, C>,Left 进 left、Right 进 right;
  • partitionMapWithIndex / partitionWithIndex:带索引版本;
  • separate:把 Either<A, B>[] 直接拆成左右两组,是 partitionMap 的“恒等映射”特例:
import { partition, separate } from 'fp-ts/Array'
import { isString } from 'fp-ts/string'
import { either } from 'fp-ts'

assert.deepStrictEqual(partition(isString)(['a', 1, {}, 'b', 5]), { left: [1, {}, 5], right: ['a', 'b'] })
assert.deepStrictEqual(separate([either.right('r1'), either.left('l1'), either.right('r2')]), {
  left: ['l1'],
  right: ['r1', 'r2'],
})

更高级的过滤

  • filterE(v2.11.0):在上下文内过滤(FilterE1<'Array'>);
  • wither / wilt(v2.6.5):Witherable 的“过滤 + 遍历”,可在 Option、Either 等效果内过滤/压缩数组,签名类型为 PipeableWither1<'Array'> / PipeableWilt1<'Array'>。

七、折叠(folding):reduce 家族

reduce / reduceRight 及带索引版本

  • reduce:从左到右折叠,初值为 b;
  • reduceWithIndex:迭代函数为 (i, b, a) => B;
  • reduceRight:从右到左,注意累加器是最后一个参数 (a, b) => B;
  • reduceRightWithIndex:(i, a, b) => B。
import { reduce, reduceRight, reduceWithIndex, reduceRightWithIndex } from 'fp-ts/Array'

assert.deepStrictEqual(reduce(5, (acc: number, cur: number) => acc * cur)([2, 3]), 30)
assert.deepStrictEqual(reduceRight('', (cur: string, acc: string) => acc + cur)(['a', 'b', 'c']), 'cba')

const f = (index: number, acc: string, cur: unknown) =>
  acc + (typeof cur === 'string' ? cur.toUpperCase() + index : '')
assert.deepStrictEqual(reduceWithIndex('', f)([2, 'a', 'b', null]), 'A1B2')

foldMap / foldMapWithIndex

先映射、再用 Monoid 折叠,是“Map-Reduce”的抽象:

import { foldMap } from 'fp-ts/Array'

const monoid = { concat: (a: string, b: string) => a + b, empty: '' }
assert.deepStrictEqual(foldMap(monoid)((s: string) => s.toUpperCase())(['a', 'b', 'c']), 'ABC')
assert.deepStrictEqual(
  foldMapWithIndex(monoid)((index, s) => `${s.toUpperCase()}(${index})`)(['a', 'b', 'c']),
  'A(0)B(1)C(2)'
)

这些函数由 Foldable1 / FoldableWithIndex1 实例提供(见下节)。


八、实例(instances):数组在类型类体系中的位置

模块导出了大量可直接复用的类型类实例(均在 src/Array.ts 中定义,测试覆盖见 test/Array.ts):

实例 版本 说明
Functor / FunctorWithIndex v2.7.0 映射能力(带索引)
Apply v2.10.0 应用 ap
Applicative v2.7.0 of + ap
Chain v2.10.0 flatMap 的类层次封装
Monad v2.7.0 单子完整实例
Alt / Alternative v2.7.0 拼接与空值语义
Compactable / Filterable / FilterableWithIndex v2.7.0 过滤压缩
Foldable / FoldableWithIndex v2.7.0 折叠
Traversable / TraversableWithIndex v2.7.0 遍历
Extend v2.7.0 上下文扩展(extend/duplicate)
Unfoldable v2.7.0 由种子展开
Witherable v2.7.0 可过滤遍历
FromEither v2.11.0 从 Either 构造
Pointed v2.10.0 最小 of
Zero v2.11.0 空数组
ChainRecBreadthFirst / ChainRecDepthFirst v2.11.0 栈安全递归(广度/深度优先)

实践建议:尽量传“小而专”的实例(如函数需要 Functor 就传 A.Functor),而不是整个大实例对象。文档“zone of death”一节明确指出旧的组合实例 array 已废弃。

基于 Eq / Ord / Show / Monoid 的派生实例

这些“get*”函数用传入的代数结构派生出数组层面的结构:

  • getEq:逐元素按 E 比较;长度不同即不相等;
  • getOrd:按字典序比较,先比首个不同的元素对,全等则更长者更大;
  • getShow:用元素 Show 渲染数组;
  • getMonoid / getSemigroup:基于数组拼接;
  • getUnionMonoid / getUnionSemigroup(v2.11.0):基于 Eq 判等的并集(重复元素只保留一次);
  • getIntersectionSemigroup(v2.11.0):交集;
  • getDifferenceMagma(v2.11.0):差集(Magma 无单位元)。
import { getEq, getOrd, getUnionMonoid, getDifferenceMagma } from 'fp-ts/Array'
import * as S from 'fp-ts/string'
import * as N from 'fp-ts/number'

const E = getEq(S.Eq)
assert.strictEqual(E.equals(['a', 'b'], ['a', 'b']), true)

const O = getOrd(S.Ord)
assert.strictEqual(O.compare(['b'], ['a']), 1)

const M = getUnionMonoid<number>(N.Eq)
assert.deepStrictEqual(M.concat([1, 2], [2, 3]), [1, 2, 3])

const D = getDifferenceMagma<number>(N.Eq)
assert.deepStrictEqual(D.concat([1, 2], [2, 3]), [1])

九、映射(mapping):map 家族与 flap

  • map:(a: A) => B 提升为 (fa: A[]) => B[],即“对每个元素应用函数并收集结果”;
  • mapWithIndex:迭代函数为 (i, a) => B;
  • flap(v2.10.0):反转方向——给定一个值,把它应用到函数数组的每个函数上:
import { map, mapWithIndex, flap } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(pipe([1, 2, 3], map((n) => n * 2)), [2, 4, 6])
assert.deepStrictEqual(pipe(['a', 'b', 'c'], mapWithIndex((i, s) => `${s} - ${i}`)), ['a - 0', 'b - 1', 'c - 2'])

const funs = [(n: number) => `Double: ${n * 2}`, (n: number) => `Triple: ${n * 3}`]
assert.deepStrictEqual(flap(4)(funs), ['Double: 8', 'Triple: 12'])

十、模式匹配(pattern matching):match 家族

数组上的“空/非空”分支处理,全部采用 data-last 柯里化:

  • match(v2.11.0):空则 onEmpty(),非空则把整个数组作为 NonEmptyArray 交给 onNonEmpty;
  • matchW:W 版本,允许两个分支返回不同类型并合并;
  • matchLeft:非空时拆为 head 与 tail;matchLeftW 为拓宽版;
  • matchRight:非空时拆为 init 与 last;matchRightW 为拓宽版;
  • foldLeft / foldRight:分别是 matchLeft / matchRight 的别名(legacy 命名)。
import { match, matchLeft, matchW } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

const matcher = match(
  () => 'No elements',
  (as) => `Found ${as.length} element(s)`
)
assert.deepStrictEqual(pipe([1, 2, 3, 4], matcher), 'Found 4 element(s)')
assert.deepStrictEqual(pipe([], matcher), 'No elements')

// 用 matchLeft 递归求长度
const len: <A>(as: Array<A>) => number = matchLeft(
  () => 0,
  (_, tail) => 1 + len(tail)
)
assert.strictEqual(len([1, 2, 3]), 3)

// matchW:两个分支类型不同
const matcherW = matchW(
  () => 'No elements',
  (as) => as.length
)
assert.deepStrictEqual(pipe([1, 2, 3, 4], matcherW), 4)

十一、精化(refinements):类型守卫

  • isEmpty:as is [] 类型守卫,判定空数组;
  • isNonEmpty:as is NEA.NonEmptyArray<A>,把数组收窄为非空数组类型。
import { isEmpty, isNonEmpty } from 'fp-ts/Array'
assert.strictEqual(isEmpty([]), true)
assert.strictEqual(isNonEmpty(['a']), true)

收窄后即可安全调用 NonEmptyArray 模块(src/NonEmptyArray.ts)中要求非空的函数。


十二、sequencing:链式与扁平化

flatMap(v2.14.0)

flatMap 是数组 Monad 的 bind:对每个元素应用返回数组的函数,再拼接结果(map + flatten)。支持数据优先与数据最后两种调用方式,且迭代函数可接收索引:

import { flatMap, map, replicate } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

const f = (n: number) => replicate(n, `${n}`)
assert.deepStrictEqual(pipe([1, 2, 3], map(f)), [['1'], ['2', '2'], ['3', '3', '3']])
assert.deepStrictEqual(pipe([1, 2, 3], flatMap(f)), ['1', '2', '2', '3', '3', '3'])

相关组合子

  • chain(legacy,v2.0.0):flatMap 的别名;
  • chainWithIndex(v2.7.0):迭代函数为 (i, a) => B[];
  • chainFirst:链式执行但只保留第一个数组的结果(副作用式链式);
  • flatten(v2.5.0):A[][] 展平为 A[];
  • chainRecBreadthFirst / chainRecDepthFirst(v2.11.0):用 Either<A, B>[] 表达递归的广度/深度优先展开,配合 ChainRec 实例实现栈安全递归。
import * as A from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(pipe([1, 2, 3], A.chainFirst(() => ['a', 'b'])), [1, 1, 2, 2, 3, 3])
assert.deepStrictEqual(A.flatten([['a'], ['b', 'c']]), ['a', 'b', 'c'])

十三、traversing:traverse / sequence / traverseWithIndex

这是数组与其它效果类型(Either、Option、Task 等)之间的“桥”。

  • traverse:对每个元素应用返回 HKT 的函数,再用 Applicative 把结果序列化——典型场景是把 (a) => Either<Error, b> 应用在整个数组上,一次性得到 Either<Error, B[]>(任一元素失败则整体失败);
  • traverseWithIndex:迭代函数带索引;
  • sequence:traverse 的恒等映射版本,把 Array<HKT<A>> 翻转为 HKT<Array<A>>(如 Array<Either<E, A>> → Either<E, Array<A>>)。
import { traverse, sequence, traverseWithIndex } from 'fp-ts/Array'
import { Applicative, left, right } from 'fp-ts/Either'

const f = (x: unknown) => (typeof x === 'string' ? right(x.toUpperCase()) : left(new Error('not a string')))
assert.deepStrictEqual(traverse(Applicative)(f)(['a', 'b']), right(['A', 'B']))
assert.deepStrictEqual(traverse(Applicative)(f)(['a', 5]), left(new Error('not a string')))

assert.deepStrictEqual(sequence(Applicative)([right('a'), right('b')]), right(['a', 'b']))

const g = (index: number, x: unknown) =>
  typeof x === 'string' ? right(x.toUpperCase() + index) : left(new Error('not a string'))
assert.deepStrictEqual(traverseWithIndex(Applicative)(g)(['a', 'b']), right(['A0', 'B1']))

在 perf/Task/sequenceArray.ts 等性能基准中,可以看到 fp-ts 官方用 sequenceArray 类用法对 Task、TaskEither 等效果做序列化的实测场景。


十四、unsafe 与索引安全操作

unsafe 系列(v2.0.0,不做边界检查)

函数 行为
unsafeDeleteAt(i, as) 删除第 i 个元素,越界时行为未定义
unsafeInsertAt(i, a, as) 插入元素,返回 NonEmptyArray
unsafeUpdateAt(i, a, as) 替换第 i 个元素

安全系列(返回 Option,越界得 None)

  • lookup(i):安全读取,pipe([1, 2, 3], lookup(1)) 得 some(2),越界得 none;
  • head / last / init / tail:取首/尾/除末/除首元素,空数组得 none;
  • deleteAt / insertAt / updateAt / modifyAt:索引写操作,越界得 none(insertAt 成功时返回 NonEmptyArray);
  • isOutOfBound(i, as):判定索引是否越界(负数与超出长度均为 true)。
import { head, lookup, deleteAt, updateAt, isOutOfBound } from 'fp-ts/Array'
import { some, none } from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(head([1, 2, 3]), some(1))
assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none)
assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3]))
assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3]))
assert.strictEqual(isOutOfBound(3, ['a', 'b', 'c']), true)

十五、utils:常用工具函数速查

增删改与拼接

  • append / appendW(v2.10.0 / v2.11.0):尾部追加,返回 NonEmptyArray;W 版允许异构类型;
  • prepend / prependW:头部插入,同理;
  • concat / concatW(v2.11.0):拼接两个数组;W 版合并类型;
  • copy:浅拷贝出一个新数组;
  • intersperse(v2.9.0):在元素之间插入分隔值;
  • prependAll(v2.10.0):在每个元素前插入分隔值;
  • intercalate(v2.12.0):插入分隔值后用 Monoid 折叠(如 intercalate(S.Monoid)('-')(['a','b','c']) → 'a-b-c')。
import { append, prepend, intersperse, intercalate, concatW } from 'fp-ts/Array'
import * as S from 'fp-ts/string'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4])
assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4])
assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4])
assert.deepStrictEqual(intercalate(S.Monoid)('-')(['a', 'b', 'c']), 'a-b-c')
assert.deepStrictEqual(pipe([1, 2], concatW(['a'])), [1, 2, 'a'])

查找与判定

  • findFirst / findLast:返回首个/末个满足谓词的元素(Option),支持 Refinement 收窄;
  • findFirstMap / findLastMap:返回首个/末个 Some 的映射结果;
  • findIndex / findLastIndex:返回满足谓词的索引(Option<number>);
  • elem:基于 Eq 判断成员资格;
  • every / some / exists:全称/存在判定;some 与 exists 成功时会把数组收窄为 NonEmptyArray。
import { findFirst, findFirstMap, findIndex, elem, some } from 'fp-ts/Array'
import { some as S, none } from 'fp-ts/Option'
import * as N from 'fp-ts/number'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(findFirst((n: number) => n > 1)([1, 2, 3]), S(2))
assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), S(1))
assert.strictEqual(pipe([1, 2, 3], elem(N.Eq)(2)), true)
assert.equal(some((x: number) => x >= 10)([1, 2, 3]), false)

子数组切分

  • takeLeft / takeRight / dropLeft / dropRight:按数量取/丢,n 归一化为非负整数;
  • takeLeftWhile / dropLeftWhile:按谓词取/丢最长前缀;
  • spanLeft:同时返回 { init, rest }(Spanned 接口);
  • splitAt(n):切成 [A[], A[]];
  • chunksOf(n):切成 n 长度的块,最后一块可更短;注意 chunksOf(n)([]) 是 [] 而非 [[]],以保证与递归定义及 concat 分配律一致;
  • chop:递归“切块”模式,函数消费数组前缀并返回 [B, A[]],常用于分组。
import { takeLeft, dropLeftWhile, spanLeft, splitAt, chunksOf, chop } from 'fp-ts/Array'
import * as N from 'fp-ts/number'
import * as A from 'fp-ts/Array'
import { Eq } from 'fp-ts/Eq'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(takeLeft(2)([1, 2, 3, 4, 5]), [1, 2])
assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5])
assert.deepStrictEqual(spanLeft((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] })
assert.deepStrictEqual(splitAt(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4, 5]])
assert.deepStrictEqual(chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]])

// chop 分组:把相邻相等元素聚为一组
const group = <A>(S: Eq<A>): ((as: Array<A>) => Array<Array<A>>) =>
  A.chop((as) => {
    const { init, rest } = pipe(as, A.spanLeft((a: A) => S.equals(a, as[0])))
    return [init, rest]
  })
assert.deepStrictEqual(group(N.Eq)([1, 1, 2, 3, 3, 4]), [[1, 1], [2], [3, 3], [4]])

chunksOf 的行为在 test/Array.ts 中有专门用例覆盖,验证其把 [1,2,3,4,5] 切成 [[1,2],[3,4],[5]]。

排序

  • sort(O):按 Ord 升序排序,返回新数组(不修改原数组);
  • sortBy(ords):按多个 Ord 依次比较(可用 contramap 从 string/number 的 Ord 派生字段排序器)。
import { sort, sortBy } from 'fp-ts/Array'
import { contramap } from 'fp-ts/Ord'
import * as S from 'fp-ts/string'
import * as N from 'fp-ts/number'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(sort(N.Ord)([3, 2, 1]), [1, 2, 3])

interface Person {
  readonly name: string
  readonly age: number
}
const byName = pipe(S.Ord, contramap((p: Person) => p.name))
const byAge = pipe(N.Ord, contramap((p: Person) => p.age))
const sortByNameByAge = sortBy([byName, byAge])

assert.deepStrictEqual(sortByNameByAge([
  { name: 'b', age: 3 }, { name: 'c', age: 2 }, { name: 'b', age: 2 },
]), [
  { name: 'b', age: 2 }, { name: 'b', age: 3 }, { name: 'c', age: 2 },
])

集合语义

  • uniq(E):按 Eq 去重,保留首次出现;
  • union(E):并集(两个数组的独特值);
  • intersection(E):交集(两数组共有元素);
  • difference(E):差集(第一个数组中不在第二个数组里的元素,顺序与引用以第一个数组为准);
  • lefts / rights:从 Either[] 中提取所有 Left / Right 值;
  • zip / zipWith:按索引配对,短数组截断长数组;unzip 是其逆操作;
  • rotate(n):整体旋转 n 步(rotate(2)([1,2,3,4,5]) → [4,5,1,2,3]);
  • reverse:反转;
  • size:元素个数(等价于 length);
  • duplicate / extend:Comonad 语义——duplicate 生成“全体后缀视图”的数组,extend(f) 对每个后缀应用 f;
  • scanLeft / scanRight:折叠但保留中间结果(如 scanLeft(10, (b, a) => b - a)([1,2,3]) → [10, 9, 7, 4]);
  • unfold:从种子迭代生成数组,直到函数返回 None;
  • comprehension:数组推导式,支持谓词过滤与任意元数输入: [ f(x, y, ...) | x ← xs, y ← ys, ..., g(x, y, ...) ];
  • zero:空数组(Monoid 构建用)。
import { uniq, union, intersection, difference, zip, unzip, scanLeft, unfold } from 'fp-ts/Array'
import * as N from 'fp-ts/number'
import { option } from 'fp-ts'
import { pipe } from 'fp-ts/function'

assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2])
assert.deepStrictEqual(pipe([1, 2], union(N.Eq)([2, 3])), [1, 2, 3])
assert.deepStrictEqual(pipe([1, 2], intersection(N.Eq)([2, 3])), [2])
assert.deepStrictEqual(pipe([1, 2], difference(N.Eq)([2, 3])), [1])
assert.deepStrictEqual(pipe([1, 2, 3], zip(['a', 'b', 'c', 'd'])), [[1, 'a'], [2, 'b'], [3, 'c']])
assert.deepStrictEqual(unzip([[1, 'a'], [2, 'b']]), [[1, 2], ['a', 'b']])
assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4])

const f = (n: number) => (n <= 0 ? option.none : option.some([n * 2, n - 1] as const))
assert.deepStrictEqual(unfold(5, f), [10, 8, 6, 4, 2])

ap / apFirst / apSecond

ap 把“函数数组”应用到“参数数组”上(笛卡尔积式应用),是 Applicative 的核心操作:

import { ap, map, of } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'

const f = (s1: string) => (n: number) => (s2: string) => s1 + n + s2

// 逐个参数展开
assert.deepStrictEqual(pipe(['a', 'b'], map(f), ap([1, 2]), ap(['😀', '😫'])), [
  'a1😀', 'a1😫', 'a2😀', 'a2😫',
  'b1😀', 'b1😫', 'b2😀', 'b2😫',
])

// 与 of(f) + ap 写法等价
assert.deepStrictEqual(pipe(of(f), ap(['a', 'b']), ap([1, 2])), pipe(['a', 'b'], map(f), ap([1, 2])))
  • apFirst:组合两个数组,保留第一个的结果;
  • apSecond:组合两个数组,保留第二个的结果。

十六、zone of death:已废弃 API 及迁移指引

以下旧 API 已废弃,文档明确标注了替代方案:

废弃 API 替代方案
array(组合大实例) 按需传小实例,如 A.Functor、A.Monad
cons prepend
empty 直接使用新的 []
prependToAll prependAll
range 使用 NonEmptyArray 模块(src/NonEmptyArray.ts)
snoc append
chain flatMap

迁移时要同步更新类型依赖:例如从 array 大实例切换到 Functor 等小实例,能获得更精确的类型推断,也符合“最小依赖”原则。


十七、实践建议与调用约定

  1. 统一导入风格:文档示例常用 import * as A from 'fp-ts/Array' 或按名导入 import { map } from 'fp-ts/Array',配合 pipe 使用 data-last 签名可读性最佳;
  2. 不可变约定:sort、reverse、rotate、updateAt 等均返回新数组,不修改原数组,符合函数式纯度;
  3. 用 Option 表达“可能缺失”:越界访问、空数组取首尾等场景优先使用 lookup、head、findFirst 等安全函数,避免手写边界判断;
  4. 跨效果遍历用 traverse/sequence:在 Either、Option、Task 等效果下批量处理数组时,优先用这两个函数获得“整体成功或整体失败”的语义;
  5. 相关模块:非空数组场景请参考 docs/modules/NonEmptyArray.ts.md 与 src/NonEmptyArray.ts;只读数组场景可参考 docs/modules/ReadonlyArray.ts.md。

总结

Array 模块把 TypeScript 原生数组完整接入 fp-ts 的类型类体系:构造(makeBy/of/replicate)、转换(fromEither/fromOption)、过滤(filterMap/partition/separate)、折叠(reduce/foldMap)、映射(map/flap)、模式匹配(match 家族)、遍历(traverse/sequence)以及一整套安全索引操作与集合语义工具。理解这些函数及其背后的单子、遍历器语义,即可在真实项目中写出类型安全、组合优雅且可测试的数组处理代码。

登录后查看全文
fp-ts