基于重排或基于对的延迟类型的表达方式是否有所不同?

时间:2019-04-05 18:39:06

标签: javascript functional-programming lazy-evaluation thunk

给出两种都代表延迟计算的类型:

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倾向于单子,而deferPair倾向于单子。我倾向于使用deferPair,因为在Javascript中执行重执行很昂贵。但是,我不确定可能存在的弊端。

2 个答案:

答案 0 :(得分:2)

  

基于重排或基于对的延迟类型的表达方式是否存在差异?

不,表达能力没有差异。每个函数及其参数(即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倾向于单子,而deferPair倾向于单子。

不,它们是等效的。 ThunkClosure都具有MonadComonad的实例:

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中执行重执行很昂贵。

谁这么说?我的基准测试显示重击执行比闭包执行更快:

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和close之间的区别。

严格的语言(例如JavaScript)中的thunk是() -> a类型的任何函数。例如,函数() => 2 + 3的类型为() -> Number。因此,这是一个沉重的负担。通过推迟计算直到调用thunk来进行thunk reifies的惰性计算。

闭包是两个元素中的任意一对,其中第一个元素是类型b -> a的函数,第二个元素是类型b的值。因此,该对具有类型(b -> a, b)。例如,对[(x, y) => x + y, [2, 3]]的类型为((Number, Number) -> Number, (Number, Number))。因此,这是一个关闭。

  

一个怪人也可以有免费的依赖项。

我将假设您的意思是自由变量。当然,一个thunk可以有自由变量。例如,() => x + 3(在词汇上下文中,x = 2是一个完全有效的重击)。同样,闭包也可以具有自由变量。例如,[y => x + y, [3]](在词汇上下文中,x = 2是完全有效的闭包)。

  

我也没有声称没有暴徒的通俗实例。

您说过“ deferThunk倾向于单子,而deferPair倾向于单子。”“倾向于”倾向于毫无意义。 deferThunk返回一个monad,否则不返回。对于deferPair和comonads也是如此。因此,我假设您的意思是说deferThunk返回一个deferPair的单子(但不是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的{​​{1}}实例:

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 实例进行类型检查,但这也不是正确的实现。因此,以下程序仍不会键入check:

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,我们只能使用xf。例如,如果不存在量化,我们可以这样做:

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,这就是应该使用闭包的方式。

答案 1 :(得分:0)

我玩过基于对的延迟计算,我认为它们至少比其thunk-counterparts更灵活。这是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”行)。

这不是理想的实现,而只是演示了在没有尾调用/尾调用对x优化的情况下,以严格的语言使用惰性评估可以达到多远的效果。对于同一主题提出太多问题,我深表歉意。当某人缺乏聪明时,坚韧是获取新知识的替代策略。