F# 在这种情况下,如何处理序列构造,因为我们不';没有中断也没有强大版本的Seq.choose?
我希望我能做到:F# 在这种情况下,如何处理序列构造,因为我们不';没有中断也没有强大版本的Seq.choose?,f#,F#,我希望我能做到: let myFun param1 param2 = ..... if condition 1 .... if condition 2 yield .... let sequence = seq { for x in xs do myFun 1 x myFun 2 x
let myFun param1 param2 =
.....
if condition 1
....
if condition 2
yield ....
let sequence = seq { for x in xs do
myFun 1 x
myFun 2 x
}
但现在我只能这样做
let myFun param =
.....
.....
if condition 1
....
if condition 2
Some....
else None // has to complete else
else None
let sequence = seq { for x in xs do
match myFun 1 x with
| Some x -> yield x
| None -> ()
match myFun 2 x with
| Some x -> yield x
| None -> ()
}
let sequence2 = // order will be different, and we can not have index passed into function unless we do a futher Seq.map
let a = xs |> Seq.choose (myFun 1)
let b = xs |> Seq.choose (myFun 2)
Seq.append a b
我的真实代码:
代码看起来不太好一些None
,我尝试了Seq.choose
,这没有多大帮助,因为它不支持Seq.choosei
let exam isForward brickID =
let brick = state.[brickID]
let (nextTR, nextOccupied, nextUnoccupied) = if isForward then brick.Body.nudgeForward () else brick.Body.nudgeBack ()
if (nextOccupied.isInGrid gridSize) && (map.ContainsKey nextOccupied |> not) then
let nextBrick = { brick with Body = nextTR }
let nextState = getNextState state brickID nextBrick
if not (explored.Contains nextState) then
let nextMap = map |> Map.remove nextUnoccupied
|> Map.add nextOccupied nextBrick
Some ((nextState, nextMap), (nextBrick, if isForward then brick.Body.Direction else brick.Body.Direction.Opposite))
else None
else None
seq { for brickID in 0 .. state.Length - 1 do
match exam true brickID with
| Some x -> yield x
| None -> ()
match exam false brickID with
| Some x -> yield x
| None -> ()
}
您的
检查
函数可以返回一个序列,该序列要么为空(而不是无
),要么只包含一个元素(而不是某些
),并使用屈服代码>将给定序列的所有元素添加到当前生成的序列中
在您的伪代码示例中,如下所示:
let myFun param1 param2 param3 = seq {
if param1 then
if param2 then
yield param3 }
let sequence = seq {
for x in xs do
yield! myFun true true x
yield! myFun true true (x * 10) }
假设xs=[1;2]
上述示例生成[1;10;2;20]
(如果您将一些true
参数设置为false
,它将跳过一些数字)在本例中,@Tomas的答案是最好的方法。但是,您仍然可以从以下位置选择使用方便的功能:
您可以将其视为Seq的自定义版本。选择
let sequence = seq { for x in xs do
yield! Option.toList (myFun 1 x)
yield! Option.toList (myFun 2 x)
}