CrystalLang-Lambda
In CrystalLang, a lambda is a type of anonymous function or a block of code that can be assigned to a variable or used inline. It encapsulates control flow, parameters, and local variables into a single package.
lambda_variable = ->(param) { puts param }
Anonymous Functions: Lambdas are also known as anonymous functions, as they don't have a name and can be treated as objects.
Usage Similar to Procs: In CrystalLang, lambdas are similar to procs but with a key distinction. Lambdas require a specific number of arguments, ensuring they are called with the correct number.
Objects in CrystalLang: Lambdas are treated as objects in CrystalLang, allowing them to be assigned to variables and passed around like other objects.
In CrystalLang, lambdas are anonymous function code blocks that can take zero or more arguments. They can then be stored or passed in other values and called primarily with the #call method.
->
(stabby lambda)
lambdas allow you to store functions inside a variable and call the method from other parts of a program.
my_lambda = -> { puts "hello" }
my_lambda.call
Output
hello
lambda = ->(name : String) { puts "Hello #{name}" }
lambda.call("geeknation")
Output
Hello geeknation
myLambda = -> (v : Int32) { v * 2 }
puts myLambda.call(2)
`
Output:
4
full_name = -> (first : String, last: String) { first + " " + last }
puts full_name.call("geek", "nation")
output
geek nation
Lambda for Return behavior
In the case of the lambda,when it comes to returning values from methods, it processed the remaining part of the method.
def my_method
x_lambda = -> {return}
x_lambda.call
p "code within the method"
end
my_method
Output
"code within the method"
Lambda while Argument count
lambdas count the arguments you pass to them:
full_name = -> (first : String, last: String) { first + " " + last }
puts full_name.call("geek", "nation", "dev")
output
error
code is tested on:
https://play.crystal-lang.org/#/cr
Subscribe to my newsletter
Read articles from GeekNation directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by