Lambda makes your Crystal functions uniformed.
鈿狅笍 It's an experiment and we do not recommend using it. It monkey patchesObject
so may cause problems using it. But it's a good example what you can do with macros.鈿狅笍
# Lambda your expression.
位 def add(x, y)
x + y
end
# Use it like a method or a function
puts 2.add 3
puts add 2, 3
Or more expressive example:
# just define a lambda
lambda def not(x) !x end
# ... and use as you wish
true.not #=> false
true.not.not #=> true
false.not #=> true
not false #=> true
not not true #=> true
not true #=> false
Add this to your application's shard.yml
:
dependencies:
lambda:
github: f/lambda.cr
A free function can be called with a syntax that looks as if the function were a member function of its first parameter type.
Idea is simple, result is awesome.
# With lambda, you can call this function ...
my_function first_param, second_param, other_param
# ... like this.
first_param.my_function x, y, z
require "lambda"
Just use 位
to make the function uniform.
位 def add(x, y)
x + y
end
result = add(2, 3) #=> 5
result = 2.add(3) #=> 5
Since you patch the struct or class you can chain easily.
result = add(2, 3).add(4).add(5) #=> 2 + 3 + 4 + 5 = 14
You can define type restrictions using the usual syntax.
位 def plus(x : Int32, y : Int32)
x + y
end
位 def plus(first : String, second : String)
first + " and " + second
end
2.plus 2 #=> 4
"fatih".plus "akin" #=> "fatih and akin"
plus 2, 2 #=> 4
plus "fatih", "akin" #=> "fatih and akin"
You can also define lambdas using blocks.
位 add do |x, y|
x + y
end
puts 2.add 3 #=> 5
puts add 2, 3 #=> 5
You can define types in parameters using param_as_Type
pattern.
位 plus do |x_as_Int32, y_as_Int32|
x + y
end
位 plus do |first_as_String, second_as_String|
first + " and " + second
end
2.plus 2 #=> 4
"fatih".plus "akin" #=> "fatih and akin"
plus 2, 2 #=> 4
plus "fatih", "akin" #=> "fatih and akin"
位 add {|x, y| x + y}
位 remove {|x| x - y}
位 multiply {|x, y| x * y}
位 divide {|x| x / y}
2.add(3).multiply(6).divide(2).remove(3).add(5).divide(5) #=> 3, It's ((((2 + 3) * 6) / 2) - 3 + 5) / 5
It's the lambda character. If you don't want to use it, you can simply use lambda
alias.
lambda add do |x, y|
x + y
end
result = add(2, 3) #=> 5
result = 2.add(3) #=> 5
- Fork it ( https://github.com/f/ufcs.cr/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
- [f] Fatih Kadir Ak谋n - creator, maintainer