Last active
August 29, 2015 14:11
-
-
Save josephlord/1ddfd6280a6bffb794dc to your computer and use it in GitHub Desktop.
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
func s(x:Int)->[Int]{ | |
return x<2 ? | |
[]: | |
// Single line closure has implicit return | |
// Closure type is Int->[Int] | |
{[$0]+s(x/$0)}( // Argment to closure | |
// Filter full range 2 to x and take first factor (non lazy) | |
// x%x is guaranteed to be 0 so safe to take first element | |
filter(2...x){x % $0 == 0}[0] | |
) | |
} | |
// With explict typed closures and a longer name | |
func shortPrimeFactors(x:Int)->[Int]{ | |
return x<2 ? | |
[]: | |
// Single line closure has implicit return | |
// Closure type is Int->[Int] | |
{(i:Int)->[Int] in [i] + shortPrimeFactors(x / i)}( | |
// Argment to closure | |
// Filter full range 2 to x and take first factor (non lazy) | |
// x%x is guaranteed to be 0 so safe to take first element | |
filter(2...x){(n:Int)->Bool in x % n == 0}[0] | |
) | |
} | |
// As above but looking like line noise/Perl | |
func p(x:Int)->[Int]{return x<2 ?[]:{[$0]+p(x/$0)}(filter(2...x){x%$0 == 0}[0])} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome - thanks for that :-) Not seen a closure type inferred by being returned by an outer function before.