# Calling an anonymous function

Hi All,

In plain Pascal, I can do this:

type
RealFunction = function(x: double): double;

function bisect(f: RealFunction; a, b: double): double;
begin
if (abs(f(a)) < 0.001) then result := a
else if (abs(f(b)) < 0.001) then result := b
else begin
// find the solution inside the interval
end;
end;

So I can declare functions like these…

function f(x: double): double;
begin
result := sin(x) - 0.5;
end;

function g(x: double): double;
begin
result := xxx-10;
end;

… and call them this way:

var
x1, x2: double;
begin
x1 := bisect(f,0,pi/2);
x2 := bisect(g,1,3);

end.

I have tried many ways to write this in Ruby but I failed to get it
working as expected. Any hint?
Thank you.

• Original reply follows - - - - - -

Maybe you are looking for #lambda?

anon_method = lambda do |x|
x + 2
end

## anon_method.call(4) #=> 6

Vale,
Quintus

I will reject HTML emails. | Ich akzeptiere keine HTML-Nachrichten.
|
Use GnuPG for mail encryption: | GnuPG für Mail-Verschlüsselung:
http://www.gnupg.org | The GNU Privacy Guard

On Sun, May 4, 2014 at 5:51 PM, Quintus [email protected] wrote:

end

## anon_method.call(4) #=> 6

This would be the way to go. One can also invoke the method via #[]:

irb(main):001:0> anon_method = lambda do |x|
irb(main):002:1* x + 2
irb(main):003:1> end
=> #<Proc:0x00000600418f60@(irb):1 (lambda)>
irb(main):004:0> anon_method[9]
=> 11

Basically with that approach anything that implements #[] or #call can
be used:

irb(main):005:0> Pluser = Struct.new :add do
irb(main):006:1* def call(x) x + add end
irb(main):007:1> alias [] call
irb(main):008:1> end
=> Pluser
irb(main):009:0> f = Pluser.new 2
=> #
irb(main):010:0> f[9]
=> 11
irb(main):011:0> f.call(9)
=> 11

Sorry for the bad class naming.

Kind regards

robert

Ruby’s syntax also allows you to pass functions in your method calls:

def bisect(x, y)
if yield(y).abs < 0.001
y
elsif yield(x).abs < 0.001
z
else
“something else”
end
end

x1 = bisect(0, Math::PI/2) { |x| Math.sin(x) - .5 }
x2 = bisect(1, 3) { |x| x**3 - 10 }

puts x1, x2