Lambda演算中的JavaScript匿名函数模拟算法,结果返回`undefined`

问题描述 投票:0回答:2

我打算使用javascript闭包来模拟lambda演算中的基本算术,以定义3 = 1 + 2像这样:

0 := λf.λx.x
1 := λf.λx.f x
2 := λf.λx.f (f x)
3 := λf.λx.f (f (f x))

它应该打印三遍hello world,现在它打印一次hello world和两次undefined。有人可以帮忙解释为什么会这样以及我的代码有什么问题吗?预先感谢。

var zero = function(f) {
  return function(x) {
    return x;
  };
};

var one = function(f) {
  return function(x) {
    return f(x);
  };
};

function add(n, m) {
  return function(f) {
    return function(x) {
      return n(f)(m(f)(x));
    };
  };
}

// test, define number two and number three in lambda calculus
var two = add(one, one);
var three = add(one, two);

// function f is to console.log
var print3times = three(value => console.log(value));
print3times("hello world")
// return:
// hello world
// undefined
// undefined
javascript anonymous-function lambda-calculus
2个回答
0
投票

关键是n(f)(m(f)(x))中的m(f)(x)返回undefined,因为它是console.log。然后,它首先运行它(并打印“ hello world”),但是在其上运行n(f)时,它将打印m(f)(x)的结果:未定义。如ASDFGerte所述,如果您添加“返回值”;对它。它将正常工作。


0
投票

您在这里。

var log = function(x) {
  console.log(x)
  return x
}

var zero = function(f) {
  return function(x) {
    return x;
  };
};

var one = function(f) {
  return function(x) {
    return f(x);
  };
};

function add(n, m) {
  return function(f) {
    return function(x) {
      return n(f)(m(f)(x));
    };
  };
}

// test, define number two and number three in lambda calculus
var two = add(one, one);
var three = add(one, two);

// function f is to console.log
var print3times = three(log);
print3times("hello world")

这是踢脚的ES6翻译:

const log = x => (console.log(x), x)

const identity = x => x

const zero = f => identity

const one = f => x => f(x)

// I took the liberty of currying add
const add = n => m => f => x => n(f)(m(f)(x))

// test, define number two and number three in lambda calculus
const two = add(one)(one)
const three = add(one)(two)

// function f is to console.log
const print3times = three(log)
print3times("hello world")
© www.soinside.com 2019 - 2024. All rights reserved.