Skip to content

Instantly share code, notes, and snippets.

View aherve's full-sized avatar

Aurélien aherve

View GitHub Profile
my_fancy_func = minus.(square, plus_one) # defining a new function
my_fancy_func.(3) #=> 5 = 3*3 - ( 3 + 1)
@aherve
aherve / ex4.rb
Last active November 24, 2016 13:42
derivative = -> f { # we take a function as argument
-> x { # the function takes a real x as argument
( f.(x+1e-3) - f.(x-1e-3) ) / ( 2e-3 ) # apply the scheme
}
}
# Let's try:
derivative_of_square = derivative.(square) => #<Proc:0x00000001b7c270@(irb):24 (lambda)> . Yay, a new function !
#Can we use it ?
second_derivative_of_square = derivative.( derivative.(square) ) # this should be a constant function that return 2
second_derivative_of_square.(2) #=> 1.999999999946489
second_derivative_of_square.(3) #=> 2.000000000279556
n_times = -> n,f {
n == 1 ? f : -> x { f.(n_times.(n-1,f).(x))}
}
nth_derivator = -> n { n_times.(n,derivate) }
derivative_of_square = nth_derivator.(1).(square) #derivate one time
second_derivative_of_square = nth_derivator.(2).(square) #derivate two times
third_derivative_of_square = nth_derivator.(3).(square) #derivate three times
p derivative_of_square.(3) # => 5.999999999999339
p second_derivative_of_square.(3) # => 2.000000000279556
p third_derivative_of_square.(3) # => 0.0
minus = -> f,g { -> x { f.(x) - g.(x) } } # f - g
div = -> f,g { -> x { f.(x) / g.(x) } } # f / g
mult = -> f,g { -> x { f.(x) * g.(x) } } # f * g
norm = -> f { -> x { f.(x).abs}} # absolute value
const = -> const { -> x { const} } # That's right, the constant function !
# You should recognize these:
plus_eps = -> eps { -> f { -> x { f.(x+eps) } } }
min_eps = -> eps { -> f { -> x { f.(x-eps) } } }
@aherve
aherve / ex10.rb
Last active November 23, 2016 15:11
lim = -> f,eps,tres {
-> x {
inf.(
norm.(
minus.(
plus_eps.(eps/2.0).(f),
plus_eps.(eps).(f)
)
), const.(tres) ).(x) ? plus_eps.(eps).(f).(x) : lim.(f,eps/2.0,tres).(x)
}
# derivative_scheme.(f).(x) shall be a function of epsilon
derivative_sheme = -> f {
-> x {
-> eps {
div.( minus.(plus_eps.(eps).(f), min_eps.(eps).(f) ), mult.(const.(2), const.(eps))).(x)
}
}
}
# And the derivative operator:
#!/usr/bin/env ruby
# Our fancy function. Could be exactly anything
square = -> x {x*x}
# some tools
minus = -> f,g { -> x { f.(x) - g.(x) } }
div = -> f,g { -> x { f.(x) / g.(x) } }
mult = -> f,g { -> x { f.(x) * g.(x) } }
norm = -> f { -> x { f.(x).abs}}
const = -> const { -> x { const} }