Filtering by Tag: functional

Functional Fizzbuzz in Swift

It's fun to revisit old programming problems with new programming styles. Today I was thinking about a nice way to rewrite the classic Fizzbuzz problem in a functional style.

It takes advantage of map() and forEach() and the fact that in Swift, map can be applied to a countable range:

If you just wanted to print the output, the map() piece can be omitted and the prints moved into the function body:

This version has the advantage of being shorter to type and only applying a single function (forEach) rather than two (map and forEach). However, the disadvantage is that IO is moved into the printfb() function whereas the original fb() function has no side effects and leaves IO to the outermost part of the program.