I'm trying to implement currying as per the the Little Schemer example eq?
given below. eq( test, testFor)
takes in a test condition and an atom and returns a function based on the passed function test
, which takes one argument to return a boolean.
Here is my code:
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
The if condition is not executed. Can someone tell me why?
To call
test
within youreq method
, you need to usetest.call
instead of justtest
.As is, the reason you're not getting an
Undefined method
or other error from yourtest(..)
expression ineq
is that there is a Kernel method namedtest
which accepts 2 or 3 parameters.To answer the question in your comment about how to return a proc which returns a proc, you "just do it". For example, you can return
Proc.new {Proc.new {puts 'foo'}}
.And since proc variables can be passed around and returned like any other variable without concern for them being accidentally "invoked", if you pass in a proc variable as an argument, you can simply return that variable, as in
Proc.new {|proc| proc}
.In your case, though, if you're trying to create a predicate based on an argument passed in, you can do the following: