Skip to content

Instantly share code, notes, and snippets.

@alskipp
Created September 8, 2014 22:02
Show Gist options
  • Save alskipp/2d81bc316926d779f185 to your computer and use it in GitHub Desktop.
Save alskipp/2d81bc316926d779f185 to your computer and use it in GitHub Desktop.
Curried, partially applied fizzBuzz Swift
// Declared as a curried function
func fizzBuzzWithOptions(opts:[(divisor: Int, str: String)]) (num: Int) -> String {
let returnString = opts.reduce(String()) { acc, opt in
num % opt.divisor == 0 ? acc + opt.str : acc
}
return returnString.isEmpty ? String(num) : returnString + "!"
}
// Can be called inline with one argument to map
let array1 = [Int](1...100).map(fizzBuzzWithOptions([(3, "Fizz"), (5, "Buzz")]))
// ["1", "2", "Fizz!", "4", "Buzz!", "Fizz!", "7", "8", "Fizz!" …]
// Or partially applied in advance
let fizzBuzzBar = fizzBuzzWithOptions([(3, "Fizz"), (5, "Buzz"), (7, "Bar")])
let array2 = [Int](1...110).map(fizzBuzzBar)
// ["1", "2", "Fizz!", "4", "Buzz!", "Fizz!", "Bar!", "8", "Fizz!" …]
@alskipp
Copy link
Author

alskipp commented Sep 8, 2014

A Swift FizzBuzz implementation, adapted from ideas found here: http://new.livestream.com/nslondon/events/3336404 by https://twitter.com/abizern
Do watch it - it's very good.

This version uses the same idea presented in the video - a function that takes an array of fizzBuzz options (in tuple form) and an Int parameter - it returns either the Int as a String or an appropriate fizzBuzz string. The advantage of the function is that fizzBuzz can easily be extended by passing in extra options.

This version adds a few extra ideas:

  • uses named tuple elements in the function declaration
  • implemented without mutable state inside the function
  • function is declared in curried form

As the function is curried it can be partially applied, which means it can be passed directly to map - no need for an explicit closure, which makes it a bit nicer to read IMHO.

The linked video also demonstrates fizzBuzz implementations using generators and sequences, so check it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment