Does Swift's standard library include a list anamorphism for a Sequence
or something similar?
An Anamorphism on lists or sequences would be the opposite of the reduce
function. So instead of collapsing a sequence down to a single value, it will build a sequence up.
reduce
takes an initial value, and a function for combining sequence elements with this, and returns a final value. It's signature looks like this (newlines added for readability):
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows
-> Result
An anamorphism for sequence might go like this:
func inflate<State, Element>(
_ initialState: State,
_ generator: @escaping (State) -> (State, Element)?)
-> AnamorphismSequence<State, Element>
By giving it some initial state, and telling it how to turn that in to an element and the next state, it can build up a sequence for you. So, I could get an array such as Array(1..<10)
like this:
Array(inflate(1) { s in s < 10 ? (s+1, s) : nil })