• [^] # Re: Ruby <3

    Posté par . En réponse à la dépêche Pendant ce temps, dans l’écosystème Ruby. Évalué à 3.

    Après avoir vu cette vidéo, la réponse pourrait être « pas grand chose » ;)

    Dans cette vidéo, on peut voir que Ruby se débrouille plutôt bien en ce qui concerne :

    • les high-order functions :
    map = proc { |f, coll| # definition of a map function
     coll.map(&f) # using Enumerable#map...
    }
    inc = proc { |x| x + 1 } # proc that adds 1 to input
    nums = [2, 3, 4] # data for us to map over
    map.call(inc, nums) # returns [3, 4, 5]
    map.(inc, nums) # syntactic sugar to hide the `call`
    • le currying :
    add = proc { |x, y| x + y }.curry # native currying
    add.(2, 3) # returns 5
    inc = add.(1) # returns an add function with first argument pre-set as 1
    inc.(2) # returns 3
    map.(inc, [2, 3, 4]) # returns [3, 4, 5]
    • la composition (de fonctions bien sûr) :
    compose = proc { |x, y|
     proc { |*args|
     x.(y.(*args))
     }
    }
    inc = add.(1) # a inc function
    add2 = add.(2) # a dec function
    add3 = compose.(inc, add2) # returns a composition of inc and dec
    add3.(4) # returns 7, equivalent to `add2(inc(4))`
    # Personal bonus, or how to be more Haskel friendly
    class Proc # Proc class monkey patched, MER IL ET FOU
     def >>(f)
     return proc { |*args|
     f.(self.(*args))
     }
     end
    end
    inc = add.(1) # an inc function
    add2 = add.(2) # a dec function
    add3 = inc >> add2 # Haskel friendly composition ;D
    add3.(4) # returns 7, equivalent to `add2(inc(4))`