Format
This commit is contained in:
parent
0d3bf40b59
commit
b2d1a6e958
@ -1,36 +1,43 @@
|
||||
export type Nil = { readonly _tag: 'Nil' };
|
||||
export type Nil = {readonly _tag: 'Nil'}
|
||||
export type Cons<A> = {
|
||||
readonly _tag: 'Cons';
|
||||
readonly head: A;
|
||||
readonly tail: List<A>;
|
||||
};
|
||||
export type List<A> = Nil | Cons<A>;
|
||||
readonly _tag: 'Cons',
|
||||
readonly head: A,
|
||||
readonly tail: List<A>,
|
||||
}
|
||||
export type List<A> = Nil | Cons<A>
|
||||
|
||||
// Constructors
|
||||
export const nil: Nil = { _tag: 'Nil' };
|
||||
export const nil: Nil = {_tag: 'Nil'}
|
||||
export const cons = <A>(head: A, tail: List<A>): List<A> => ({
|
||||
_tag: 'Cons',
|
||||
head,
|
||||
tail,
|
||||
});
|
||||
})
|
||||
|
||||
// Operations
|
||||
type ListMap = <A, B>(f: (a: A) => B) => (fa: List<A>) => List<B>;
|
||||
export const listMap: ListMap = (f) => (fa) =>
|
||||
fa._tag === 'Cons' ? cons(f(fa.head), listMap(f)(fa.tail)) : nil;
|
||||
type ListMap = <A, B>(f: (a: A) => B) => (fa: List<A>) => List<B>
|
||||
export const listMap: ListMap = f => fa =>
|
||||
fa._tag === 'Cons' ? cons(f(fa.head), listMap(f)(fa.tail)) : nil
|
||||
|
||||
type ListReduce = <A, B>(
|
||||
f: (b: B, a: A) => B,
|
||||
initial: B
|
||||
) => (fa: List<A>) => B;
|
||||
export const listReduce: ListReduce = (f, initial) => (fa) =>
|
||||
fa._tag === 'Cons' ? listReduce(f, f(initial, fa.head))(fa.tail) : initial;
|
||||
initial: B,
|
||||
) => (fa: List<A>) => B
|
||||
export const listReduce: ListReduce = (f, initial) => fa =>
|
||||
fa._tag === 'Cons' ? listReduce(f, f(initial, fa.head))(fa.tail)
|
||||
: initial
|
||||
|
||||
// Helpers
|
||||
type FromArray = <A>(arr: Array<A>) => List<A>;
|
||||
type FromArray = <A>(arr: Array<A>) => List<A>
|
||||
export const fromArray: FromArray = <A>(arr: Array<A>) =>
|
||||
arr.reduceRight((acc: List<A>, val: A) => cons(val, acc), nil as List<A>);
|
||||
arr.reduceRight(
|
||||
(acc: List<A>, val: A) => cons(val, acc),
|
||||
nil as List<A>,
|
||||
)
|
||||
|
||||
type ToArray = <A>(fa: List<A>) => Array<A>;
|
||||
type ToArray = <A>(fa: List<A>) => Array<A>
|
||||
export const toArray: ToArray = <A>(fa: List<A>) =>
|
||||
listReduce<A, Array<A>>((acc, val) => [...acc, val], [] as Array<A>)(fa);
|
||||
listReduce<A, Array<A>>(
|
||||
(acc, val) => [...acc, val],
|
||||
[] as Array<A>,
|
||||
)(fa)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user