3 ms·
> In Haskell, by way of comparison, any one-parameter function can be used as the argument to map Ruby doesn’t have functions, but any one parameter block (to
by dragonwriter 3y ago
> In Haskell, by way of comparison, any one-parameter function can be used as the argument to map
Ruby doesn’t have functions, but any one parameter block (to which any one parameter callable, and some other things, can be converted with an &) can be passed as the block parameter to map. And, yes, you can use function composition and similar operations to build up more complex callables from existing ones without an explicit new block or lambda.
Your examples mostly have pretty close parallels in ruby:
irb(main):044:0> ["hello", "goodbye"].map &:reverse
=> ["olleh", "eybdoog"]
is the more compact form of the form with the explicit lambda:
irb(main):045:0> ["hello", "goodbye"].map {|s| s.reverse}
=> ["olleh", "eybdoog"]
composition works similarly, though there is no compact notation to convert an operator and its right operand to a callable, only the left:
irb(main):048:0> ["a","bb","ccc","dddd"].filter &(2.method(:<) << :length.to_proc)
=> ["ccc", "dddd"]
But, you do have to cheat a little to do:
irb(main):049:0> [[1,2],[3,4]].map &:*.to_proc.uncurry
=> [2, 12]
in place of:
irb(main):049:0> [[1,2],[3,4]].map {|x, y| x * y}
=> [2, 12]
Because while ruby has Proc#curry, it lacks Proc#uncurry. But its simple to define:
class Proc
def uncurry
->(args) { self.call *args }
end
end
- jonahx 3y ago> ghci> filter (\x -> (length x) > 2) ["a","bb","ccc","dddd"] ["ccc","dddd"]... I find the Haskell syntax concise and clear... > ["a","bb","ccc","dddd"].filter &(2.method(:<) << :length.to_proc) I can't imagine a stronger case for GP's thesis. The point-free ruby rewrite is so baroque and needlessly circuitous... the extra variable is a far lesser evil, and more concise: ["a","bb","ccc","dddd"].filter { |x| x.length > 2 }
- inopinatus 3y agomy instinct is ["a","bb","ccc","dddd"].grep /.../ but then, I'm a recovering perl hacker
- jonahx 3y agoLove it!
- dragonwriter 3y agoYeah, mirroring the Haskell code, while possible in Ruby, is definitely not the best Ruby-aware approach, either for concision or clarity. The composability is available, but the problems where it is the best solution are different.
- deleted 3y ago[deleted]
- inopinatus 3y agoEven without patching the standard library: irb> [[1,2],[3,4]].each_with_object(:*).map(&:reduce) => [2, 12] Given the mechanics of this I wouldn't claim it meets a strict definition of point-free, but that's an iterated application of operator-like methods omitting any explicit named/positional argument references.