Created
September 8, 2014 22:02
-
-
Save alskipp/2d81bc316926d779f185 to your computer and use it in GitHub Desktop.
Curried, partially applied fizzBuzz Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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!" …] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.