Last active
February 22, 2018 08:31
-
-
Save egnha/2efd4e2b173e2d2f4fe91490a815f62e to your computer and use it in GitHub Desktop.
Cartesian power (non-lazy)
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
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