Ananymous Functions

Prasath Ram

1 min read

When I start with ruby i always get confused about ananymous functions.
Thanks to functional programming languages it gives me the complete knowledge about about ananymous functions.
So here is what the short explanation about ananymous functions in ruby and erlang

Ananymous Functions?
Ananymous Functions are functions which does not have any names. mostly used in higher order functions, first class functions and some concepts like currying and closures
Erlang way of doing things:
Erlang has it own ananymous function called Fun method. Here two good ways in erlang to use ananymous function
Methods which accepts ananymous functions and method which returns (First class Functions)
Examples:
[source language=”ruby”]
lists:map(fun(X) -> X*X end, [2, 3]). => [4, 9]
[/source]
The map function in lists module has 2 arity(Num of params) the first one is the fun method which is a ananymous function and the second one list of integers(Array) and return list of squared integers
Method which returns a ananymous functions (Higher order functions)
[source language=”ruby”]
Square -> fun(X) -> X * X end.
[/source]
The square method return an ananymous function which can be called any time with a param to get the squared result.
Ruby has its way to go:
Ruby has its own ananymous function lambda which will be converted into proc object which can be called any time with any params
There are few methods in rails which accepts lambda method in rails (validation on Active record, nested_attributes, before_filter)
You can also write your own higher order functions on ruby to return a proc object.
Two more important concepts i would like to give a small introduction on using lambda
currying:
Currying is transforming a function from multiple inputs to fewer inputs
Example:
[source language=”ruby”]
def multiplier(given)
lambda {|num| num .to_f * given.to_f}
end
double = multiplier(2); double.call(4) => 8
triple = multiplier(3); triple.call(4) => 12
[/source]
Closures:
Possibly we are using lot of closures in ruby with out knowing its actual meaning.
am not going deeper into closure topic rather i give a small example of closure with lambda
[source language=”ruby”]
@value = 1
def print
lambda {puts “#{@value}”}
end
print.call => prints 1
[/source]
on changing the state of the instance variable @value will reflect in the result

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *