func unfoldr<A, B>(_ f: @escaping (B) -> (A, B)?) -> (B) -> UnfoldFirstSequence<A> {
return { b in sequence(
first: b, next: { x in
switch f(x) {
case .some(let(a, b)):
return Optional(a)
default:
return Optional.none
}
}
)
}
}
With this definition, I am getting the following error:
Cannot convert value of type 'B' to expected argument type 'A'.
Is there some way of solving this issue and definining this function ?
Your sequence doesn't seem to be a
UnfoldFirstSequence. Your sequence seems to have a stateB, andfis responsible for producing a new state and an element for the sequence. AnUnfoldFirstSequencehas no state that you can control. You can only produce the next element from the previous element.Your sequence can be modelled by the more general
UnfoldSequence, which has aStategeneric parameter. In fact, anUnfoldFirstSequence<T>is just anUnfoldSequence<T, (T?, Bool)>! See why the former is a special case of the latter by reading the source code :)You can create such a sequence using
sequence(state:next:).Example: