Created
February 10, 2015 19:16
-
-
Save kazk/95b8a6bc48e9042dbbc5 to your computer and use it in GitHub Desktop.
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
// MARK: unfoldr :: (T, (T)->(U, T)?) -> [U] | |
// http://hackage.haskell.org/package/base-4.7.0.2/docs/Data-List.html#v:unfoldr | |
public func unfoldr<T, U>(var seed: T, f: (T)->(U, T)?) -> SequenceOf<U> { | |
return SequenceOf {_ -> GeneratorOf<U> in | |
return GeneratorOf { | |
if let (a, b) = f(seed) { | |
seed = b | |
return a | |
} | |
return nil | |
} | |
} | |
} | |
// unfoldr(10, {($0 == 0) ? nil : ($0, $0 - 1)}).array | |
// => [10,9,8,7,6,5,4,3,2,1] | |
// unfoldr(1, {($0, 2*$0)}) // sequence of power of two | |
// fibonacci sequence | |
// unfoldr((0, 1), {($0.0, ($0.1, $0.0 + $0.1))}) | |
//=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment