As it stands, func
doesn't type check because we can't construct the infinite type t a ~ (a -> b) -> t b
. However, we can get around that restriction by creating a new data type as follows.
// Chain :: (forall b. (a -> b) -> Chain b) -> Chain a
const Chain = chain => ({ chain });
// func :: a -> Chain a
const func = x => Chain(k => func(k(x)));
// add :: Number -> Number -> Number
const add = x => y => x + y;
// trace :: a -> a
const trace = x => {
console.log(x);
return x;
};
// Chain Number
func(1).chain(add(2)).chain(add(2)).chain(trace);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…