2012-06-11 46 views
0
let tag:String = "+1" 
for str in readFile do 
    let feature = str.Split [|' '; '\t'|] 
    if feature.[8] = "0" then 
     tag = "-1" 
    else 
     tag = "+1" 

    printf "\n%s %s\n" feature.[8] tag 

如果特征[8],代码更改尝试将tag的值更改为“-1”。为0,否则为“+1”。然而,标签变量值始终保持“+1”,而不管值的特征如何。是。F#中的标志变量不变F#

如何处理基于F#中条件语句的简单值更改?

回答

2

@约翰 - 帕尔默有你的答案,但我会有点给它添加...

需要注意的是,为什么你的代码编译,但像您期望的不工作的原因是因为=操作在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" 
2

您需要使用可变变量 - 默认情况下,F#中的变量是常量。另外,<-是赋值运算符。

let mutable tag:String = "+1" 
for str in readFile do 
    let feature = str.Split [|' '; '\t'|] 
    if feature.[8] = "0" then 
     tag <- "-1" 
    else 
     tag <- "+1" 

    printf "\n%s %s\n" feature.[8] tag 
1
for str in readFile do 
    let feature = str.Split [|' '; '\t'|] 
    let tag = if feature.[8] = "0" then "-1" else "+1" 

    printf "\n%s %s\n" feature.[8] tag