Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的小阴谋家咖喱示例_Ruby_Proc_The Little Schemer - Fatal编程技术网

Ruby中的小阴谋家咖喱示例

Ruby中的小阴谋家咖喱示例,ruby,proc,the-little-schemer,Ruby,Proc,The Little Schemer,我试图按照下面给出的小Schemer示例eq?实现curryeq(test,testFor)接受一个测试条件和一个原子,并基于传递的函数test返回一个函数,该函数使用一个参数返回布尔值 这是我的密码: def eq( test, s) Proc.new { |x| test(s,x)} end eqToCarrot = eq(Proc.new{|x,y| x==y},"carrot") if eqToCarrot.call("carrot") puts "Equal!" e

我试图按照下面给出的小Schemer示例
eq?
实现curry
eq(test,testFor)
接受一个测试条件和一个原子,并基于传递的函数
test
返回一个函数,该函数使用一个参数返回布尔值

这是我的密码:

def eq( test, s)
    Proc.new { |x| test(s,x)}
end

eqToCarrot = eq(Proc.new{|x,y| x==y},"carrot")

if eqToCarrot.call("carrot")
    puts "Equal!"
end

不执行if条件。有人能告诉我为什么吗?

要在
eq方法中调用
test
,您需要使用
test。调用
而不仅仅是
test

同样,从
eq
中的
test(..)
表达式中没有得到
Undefined方法或其他错误的原因是有一个名为
test
的内核方法,它接受2或3个参数

要回答您评论中关于如何返回返回proc的问题,您可以“直接执行”。例如,您可以返回
Proc.new{Proc.new{put'foo'}}

由于proc变量可以像任何其他变量一样传递和返回,而不必担心它们被意外“调用”,如果您将proc变量作为参数传入,您只需返回该变量,如
proc.new{proc | proc}
中所示

但是,在您的情况下,如果您试图基于传入的参数创建谓词,则可以执行以下操作:

def make_eq_proc(match_string)
  Proc.new {|arg_string| arg_string == match_string}
end

eq_carrot = make_eq_proc('carrot')

eq_carrot.call('carrot') # => true

那么一个函数如何返回一个proc,而这个proc又返回一个proc呢?我现在不能回答,但是如果没有其他人回复你,我会在几个小时后回复。实际上我也想将谓词作为proc传递,这可能吗?@AmanGupta肯定。不过,我有点迷茫,在“proc which returns a proc”中的哪个proc接受谓词作为参数。两个进程的方法签名和要传入的谓词的方法签名是什么?好的,基本上我想要一个函数,它接受一个谓词(一个返回bool的函数)和一个参数,并返回一个函数,该函数接受一个将谓词应用于原始参数的参数。我说得够清楚了吗?