定义通用展开函数
Defining a generic unfoldr function
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
}
}
)
}
}
使用此定义,我收到以下错误:
Cannot convert value of type 'B' to expected argument type 'A'.
有什么方法可以解决这个问题并定义这个函数吗?
您的序列似乎不是 UnfoldFirstSequence
。您的序列似乎有一个状态 B
,并且 f
负责为序列生成一个新状态和一个元素。 UnfoldFirstSequence
没有您可以控制的状态。您只能从前一个元素生成下一个元素。
你的序列可以用更通用的UnfoldSequence
, which has a State
generic parameter. In fact, an UnfoldFirstSequence<T>
is just an UnfoldSequence<T, (T?, Bool)>
! See why the former is a special case of the latter by reading the source code :)
建模
您可以使用 sequence(state:next:)
创建这样的序列。
func unfoldr<A, B>(_ f: @escaping (B) -> (A, B)?) -> (B) -> UnfoldSequence<A, B> {
return {
sequence(state: [=10=]) { x in
guard let (a, b) = f(x) else {
return nil
}
x = b
return a
}
}
}
示例:
let seq = unfoldr { x -> (String, Int)? in
if x == 10 {
return nil
} else {
return ("\(x)", x + 1)
}
}
seq(0).forEach { print([=11=]) }
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
}
}
)
}
}
使用此定义,我收到以下错误:
Cannot convert value of type 'B' to expected argument type 'A'.
有什么方法可以解决这个问题并定义这个函数吗?
您的序列似乎不是 UnfoldFirstSequence
。您的序列似乎有一个状态 B
,并且 f
负责为序列生成一个新状态和一个元素。 UnfoldFirstSequence
没有您可以控制的状态。您只能从前一个元素生成下一个元素。
你的序列可以用更通用的UnfoldSequence
, which has a State
generic parameter. In fact, an UnfoldFirstSequence<T>
is just an UnfoldSequence<T, (T?, Bool)>
! See why the former is a special case of the latter by reading the source code :)
您可以使用 sequence(state:next:)
创建这样的序列。
func unfoldr<A, B>(_ f: @escaping (B) -> (A, B)?) -> (B) -> UnfoldSequence<A, B> {
return {
sequence(state: [=10=]) { x in
guard let (a, b) = f(x) else {
return nil
}
x = b
return a
}
}
}
示例:
let seq = unfoldr { x -> (String, Int)? in
if x == 10 {
return nil
} else {
return ("\(x)", x + 1)
}
}
seq(0).forEach { print([=11=]) }