@约翰 - 帕尔默有你的答案,但我会有点给它添加...
需要注意的是,为什么你的代码编译,但像您期望的不工作的原因是因为=
操作在tag = "-1"
和tag = "+1"
的上下文中使用是相等运算符。所以这些表达式是有效的,但返回值为bool
。但是,您应该收到以下警告:
此表达式应具有类型'单元',但类型为'bool'。使用 'ignore'放弃表达式的结果,或者'let'将 结果绑定到名称。
在您的F#编码冒险中,您会注意到这个警告。
另外请注意,你可以写(除其他替代功能的方法)使用Seq.fold您在纯功能的单向算法(不包括可变的变量):
let tag =
readFile
|> Seq.fold
//we use the wild card match _ here because don't need the
//tag state from the previous call
(fun _ (str:string) ->
let feature = str.Split [|' '; '\t'|]
//return "-1" or "+1" from the if/then expression,
//which will become the state value in the next call
//to this function (though we don't use it)
if feature.[8] = "0" then
"-1"
else
"+1")
("+1") //the initial value of your "tag"