Skip to content

Instantly share code, notes, and snippets.

@nickserv
Last active August 29, 2015 13:57
Show Gist options
  • Save nickserv/9405859 to your computer and use it in GitHub Desktop.
Save nickserv/9405859 to your computer and use it in GitHub Desktop.
Nested sums in Ruby and Haskell
mapSum :: Num a => (a -> a) -> [a] -> a
mapSum f xs = sum $ map f xs
nestedSum :: Num a => [a] -> [a] -> (a -> a -> a) -> a
nestedSum xs ys f = mapSum (\ x -> mapSum (f x) ys) xs
def nested_sum(outer, inner)
outer.reduce(0) do |outer_sum, i|
outer_sum + inner.reduce(0) do |inner_sum, j|
inner_sum + yield(i, j)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment