Last active
August 29, 2015 14:03
-
-
Save sdarlington/e6047fcf1ea5cdffd117 to your computer and use it in GitHub Desktop.
FizzBuzz
This file contains hidden or 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
import Foundation | |
func genericFizzBuzz<T> (number:T, tests:Array<(T)->String?>) -> String { | |
// Run each of the defined test replacements | |
let out = tests.map { t in t(number) } | |
// convert the nil's to empty strings | |
.map { v in v ?? "" } | |
// Concatenate all the replacements together | |
.reduce("", combine: +) | |
// Yes, this would be easier if the mapping function returned | |
// String rather than String?. I'm trying to learn about the | |
// type system and especially optionals | |
if out.isEmpty { | |
return "\(number)" | |
} | |
else { | |
return out | |
} | |
} | |
func fizzBuzz (number:Int) -> String { | |
func subBuzz (divisor:Int,s:String) -> (Int)->String? { | |
return { | |
(n:Int) -> String? in | |
if n % divisor == 0 { | |
return s | |
} | |
else { | |
return nil | |
} | |
} | |
} | |
let fizz = subBuzz(3, "Fizz") | |
let buzz = subBuzz(5, "Buzz") | |
return genericFizzBuzz(number, [ fizz, buzz ]) | |
} | |
func fizzBuzzString (number:String) -> String { | |
func subBuzz (divisor:String,s:String) -> (String)->String? { | |
return { | |
(n:String) -> String? in | |
if n.rangeOfString(divisor, options:.CaseInsensitiveSearch) { | |
return s | |
} | |
else { | |
return nil | |
} | |
} | |
} | |
let fizz = subBuzz("three", "Fizz") | |
let buzz = subBuzz("five", "Buzz") | |
return genericFizzBuzz(number, [ fizz, buzz ]) | |
} | |
for a in 1...15 { | |
fizzBuzz(a) | |
} | |
for a in ["one","two","Three", "five", "threeFive"] { | |
fizzBuzzString(a) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment