给定两种类型都表示延迟计算:
const deferThunk = thunk =>
({run: thunk});
const deferPair = (f, args) =>
({run: [f, args]});
const tap = f => x => (f(x), x);
const log = console.log;
const tx = deferThunk(
() => tap(log) ("thunk based" + " " + "deferred computations"));
const ty = deferPair(
([x, y, z]) => tap(log) (x + y + z), ["pair based", " ", "deferred computations"]);
log("nothing happened yet...")
tx.run();
ty.run[0] (ty.run[1]);
一个重要的区别似乎是deferThunk
倾向于monad,而deferPair
倾向于comonad。我倾向于选择deferPair
,因为在Javascript中thunk执行很昂贵。但是,我不确定可能的缺点。
基于thunk或pair的延迟类型的表现力是否存在差异?
不,表现力没有区别。每个函数及其参数(即closure)等同于thunk,每个thunk等同于一个闭包,它接受单元类型作为输入:
{-# LANGUAGE ExistentialQuantification #-}
import Control.Comonad
newtype Thunk a = Thunk { runThunk :: () -> a }
data Closure a = forall b. Closure (b -> a) b
runClosure :: Closure a -> a
runClosure (Closure f x) = f x
toThunk :: Closure a -> Thunk a
toThunk (Closure f x) = Thunk (\() -> f x)
toClosure :: Thunk a -> Closure a
toClosure (Thunk f) = Closure f ()
一个重要的区别似乎是
deferThunk
倾向于monad,而deferPair
倾向于comonad。
不,他们是等同的。 Thunk
和Closure
都有Monad
和Comonad
的实例:
instance Functor Thunk where
fmap f (Thunk g) = Thunk (f . g)
instance Applicative Thunk where
pure = Thunk . pure
Thunk f <*> Thunk g = Thunk (f <*> g)
instance Monad Thunk where
Thunk f >>= g = g (f ())
instance Comonad Thunk where
extract (Thunk f) = f ()
duplicate = pure
instance Functor Closure where
fmap f (Closure g x) = Closure (f . g) x
instance Applicative Closure where
pure a = Closure (pure a) ()
Closure f x <*> Closure g y = Closure (\(x, y) -> f x (g y)) (x, y)
instance Monad Closure where
Closure f x >>= g = Closure (runClosure . g . f) x
instance Comonad Closure where
extract = runClosure
duplicate = pure
我倾向于选择
deferPair
,因为在Javascript中thunk执行很昂贵。
谁说的?我的基准测试显示thunk执行比闭包执行更快:
const thunk = () => 2 + 3;
const closureFunction = (x, y) => x + y;
const closureArguments = [2, 3];
const expected = 5;
const iterations = 10000000;
console.time("Thunk Execution");
for (let i = 0; i < iterations; i++) {
const actual = thunk();
console.assert(actual, expected);
}
console.timeEnd("Thunk Execution");
console.time("Closure Execution");
for (let i = 0; i < iterations; i++) {
const actual = closureFunction(...closureArguments);
console.assert(actual, expected);
}
console.timeEnd("Closure Execution");
我无法区分thunk和closure之间的区别。
像JavaScript这样的严格语言的thunk是() -> a
类型的任何函数。例如,函数() => 2 + 3
的类型为() -> Number
。因此,这是一个thunk。通过推迟计算直到调用thunk来进行thunk reifies懒惰评估。
闭包是任意一对两个元素,其中第一个元素是b -> a
类型的函数,第二个元素是b
类型的值。因此,该货币对具有(b -> a, b)
类型。例如,货币对[(x, y) => x + y, [2, 3]]
的类型为((Number, Number) -> Number, (Number, Number))
。因此,这是一个关闭。
thunk也可以有自由依赖。
我假设你的意思是自由变量。当然,thunk可以有自由变量。例如,() => x + 3
,在词汇语境中的x = 2
,是一个完全有效的thunk。同样,闭包也可以有自由变量。例如,[y => x + y, [3]]
,在词汇语境中的x = 2
,是一个完全有效的闭包。
我也没有声称没有thon的comonad实例。
你说“deferThunk
倾向于monad,而deferPair
倾向于comonad。”这句话“倾向于”毫无意义。要么deferThunk
返回monad,要么不返回monad。同样对于deferPair
和comonads。因此,我认为你的意思是说deferThunk
为deferPair
返回一个monad(但不是comonad),反之亦然。
Thunk没有上下文,所以构建一个comonad有点奇怪,对吧?
为什么你认为thunk不能有上下文?你自己说过“thunk也可以有自由依赖。”而且,构建一个comonad实例并不是很奇怪。是什么让你觉得这很奇怪?
此外,您使用存在来避免LHS上的
b
。我不完全理解这一点,但它不符合我的代码,它使用普通的对。并且一对给出了上下文,因此是comonad实例。
我也使用普通的一对。将Haskell代码翻译成JavaScript:
// Closure :: (b -> a, b) -> Closure a
const Closure = (f, x) => [f, x]; // constructing a plain pair
// runClosure :: Closure a -> a
const runClosure = ([f, x]) => f(x); // pattern matching on a plain pair
只有进行类型检查才需要存在量化。考虑Applicative
的Closure
实例:
instance Applicative Closure where
pure a = Closure (pure a) ()
Closure f x <*> Closure g y = Closure (\(x, y) -> f x (g y)) (x, y)
因为我们使用了存在量化,所以我们可以编写以下代码:
replicateThrice :: Closure (a -> [a])
replicateThrice = Closure replicate 3
laugh :: Closure String
laugh = Closure reverse "ah"
laughter :: Closure [String]
laughter = replicateThrice <*> laugh
main :: IO ()
main = print (runClosure laughter) -- ["ha", "ha", "ha"]
如果我们不使用存在量化,那么我们的代码就不会输入检查:
data Closure b a = Closure (b -> a) b
runClosure :: Closure b a -> a
runClosure (Closure f x) = f x -- this works
instance Functor (Closure b) where
fmap f (Closure g x) = Closure (f . g) x -- this works too
instance Applicative (Closure b) where
pure a = Closure (pure a) () -- but this doesn't work
-- Expected pure :: a -> Closure b a
-- Actual pure :: a -> Closure () a
pure a = Closure (pure a) undefined -- hack to make it work
-- and this doesn't work either
Closure f x <*> Closure g y = Closure (\(x, y) -> f x (g y)) (x, y)
-- Expected (<*>) :: Closure b (a -> c) -> Closure b a -> Closure b c
-- Actual (<*>) :: Closure b (a -> c) -> Closure b a -> Closure (b, b) c
-- hack to make it work
Closure f x <*> Closure g y = Closure (\x -> f x (g y)) x
即使我们可以以某种方式让Applicative
实例进行类型检查,但这不是一个正确的实现。因此,以下程序仍然不会键入检查:
replicateThrice :: Closure Int (a -> [a])
replicateThrice = Closure replicate 3
laugh :: Closure String String
laugh = Closure reverse "ah"
laughter :: Closure Int [String]
laughter = replicateThrice <*> laugh -- this doesn't work
-- Expected laugh :: Closure Int String
-- Actual laugh :: Closure String String
如您所见,我们希望(<*>)
具有以下类型:
(<*>) :: Closure b (a -> c) -> Closure d a -> Closure (b, d) c
如果我们有这样的功能,那么我们可以写:
replicateThrice :: Closure Int (a -> [a])
replicateThrice = Closure replicate 3
laugh :: Closure String String
laugh = Closure reverse "ah"
laughter :: Closure (Int, String) [String]
laughter = replicateThrice <*> laugh
main :: IO ()
main = print (runClosure laughter) -- ["ha", "ha", "ha"]
因为我们不能这样做,所以我们使用存在量化来隐藏类型变量b
。因此:
(<*>) :: Closure (a -> b) -> Closure a -> Closure b
此外,使用存在量化强制执行给定Closure f x
的约束我们只能通过将f
应用于x
来使用f
和x
。例如,如果没有存在量化,我们可以这样做:
replicateThrice :: Closure Int (a -> [a])
replicateThrice = Closure replicate 3
useReplicateThrice :: a -> [a]
-- we shouldn't be allowed to do this
useReplicateThrice = let (Closure f x) = replicateThrice in f 2
main :: IO ()
main = print (useReplicateThrice "ha") -- ["ha", "ha"]
但是,通过存在量化,上述程序不会进行类型检查。我们只允许将f
应用于x
,这就是应该如何使用封闭。
我玩了基于对的延迟计算,我认为它们至少比他们的thunk同行更灵活。这是Haskell对Javascript的定点组合器的堆栈安全端口:
// data constructor
const structure = type => cons => {
const f = (f, args) => ({
["run" + type]: f,
[Symbol.toStringTag]: type,
[Symbol("args")]: args
});
return cons(f);
};
// trampoline
const tramp = f => (...args) => {
let acc = f(...args);
while (acc && acc.type === recur) {
let [f, ...args_] = acc.args; // (A)
acc = f(...args_);
}
return acc;
};
const recur = (...args) =>
({type: recur, args});
// deferred type
const Defer = structure("Defer")
(Defer => (f, ...args) => Defer([f, args]))
// fixed-point combinators
const defFix = f => f(Defer(defFix, f));
const defFixPoly = (...fs) =>
defFix(self => fs.map(f => f(self)));
// mutual recursive functions derived from fixed-point combinator
const [isEven, isOdd] = defFixPoly(
f => n => n === 0
? true
: recur(f.runDefer[0] (...f.runDefer[1]) [1], n - 1),
f => n => n === 0
? false
: recur(f.runDefer[0] (...f.runDefer[1]) [0], n - 1));
// run...
console.log(
tramp(defFix(f => x =>
x === Math.cos(x)
? x
: recur(
f.runDefer[0] (...f.runDefer[1]),
Math.cos(x)))) (3)); // 0.7390851332151607
console.log(
tramp(isEven) (1e6 + 1)); // false
请注意,不仅延迟类型是基于成对的,还包括合并的蹦床(见“A”行)。
这不是一个理想的实现,只是演示了在没有尾调用/尾调用modulo x优化的情况下,我们可以用严格的语言进行延迟评估。对于就同一主题提出太多问题,我深表歉意。当某人缺乏聪明才智时,坚韧是获取新知识的另一种策略。