4 ms·
stouset is obviously not arguing that the ruby version with "&:" is immediately obvious to any programmer. The point is if you know ruby, you will understand th
by Falling3 14y ago
stouset is obviously not arguing that the ruby version with "&:" is immediately obvious to any programmer. The point is if you know ruby, you will understand that line a lot quicker than the second example.
- pacala 14y agoWhat is the "fold" variant in Ruby? Maps are trivial either way, but folds are a pita in my functional programming experience.
- bjeanes 13y ago[1, 2, 3, 4, 5].reduce(0, &:+) #=> 15 Which is short hand for: [1, 2, 3, 4, 5].reduce(0) { |memo, item| memo + item } #=> 15
- dan-k 13y agoWith reduce you don't even need to use the & notation, it has that syntactic sugar built in, so you can just do this: [1, 2, 3, 4, 5].reduce(:+)
- pacala 13y agoYes and no. In practice, you're going to fold into a different domain, which causes the types of the reduce function arguments to be different. Moreover, you are not going to have your reduce function conveniently in a library. You are going to have to write a loop body. At which point, choosing a block over a for loop becomes purely religious.
- krichman 13y agoDifferent domain is fine. [1,2,3].reduce([], &:unshift) #=> [3,2,1] I don't see a problem with writing a for loop, but I think it's not as composable and it can be a little harder to read. So I don't think it's purely religious but it's close to that.
- pacala 13y agoRandomly searching for foldr on code.google.com inserts :: [(VarId,VarId)] -> Env -> Env inserts vvs env = foldr (\(a,b) acc -> M.insert a b acc) env vvs or inserts(vvs, env) { for ((a, b) : vvs) { env = M.insert(a, b, env) } return env } Pick your poison, but I'll stick with fors. Go blues!
- krichman 13y agoIf you want inscrutable Haskell you should go with the <$> operators :) I'd personally still rather have a vvs.reduce(env){|env, (a,b)| M.insert(a, b, env)} but the for loop is perfectly readable also because it fits on a single line. I think for longer bodied reduces I might prefer a for loop actually.