Skip to content

Instantly share code, notes, and snippets.

@josephlord
Last active August 29, 2015 14:11
Show Gist options
  • Save josephlord/1ddfd6280a6bffb794dc to your computer and use it in GitHub Desktop.
Save josephlord/1ddfd6280a6bffb794dc to your computer and use it in GitHub Desktop.
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])}
@ColinEberhardt
Copy link

Awesome - thanks for that :-) Not seen a closure type inferred by being returned by an outer function before.

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