Skip to content

Instantly share code, notes, and snippets.

@egnha
Last active February 22, 2018 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egnha/2efd4e2b173e2d2f4fe91490a815f62e to your computer and use it in GitHub Desktop.
Save egnha/2efd4e2b173e2d2f4fe91490a815f62e to your computer and use it in GitHub Desktop.
Cartesian power (non-lazy)
import Foundation
infix operator ^^
func ^^<A>(_ values: [A], _ exponent: Int) -> [[A]]? {
guard exponent >= 0 else { return nil }
func product(prod: [[A]], xs: [A]) -> [[A]] {
return prod.flatMap { p in xs.map { x in p + [x] } }
}
let factors = [[A]](repeating: values, count: exponent)
return factors.reduce([[]], product)
}
/*
[1, 2, 3] ^^ -1
[1, 2, 3] ^^ 0
[1, 2, 3] ^^ 3
[Int]() ^^ 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment