Question

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?

Was it helpful?

Solution

To call test within your eq method, you need to use test.call instead of just test.

As is, the reason you're not getting an Undefined method or other error from your test(..) expression in eq is that there is a Kernel method named test 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:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top