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
The code changes tries to change the value of tag to “-1” if feature.[8] is 0, or “+1” otherwise. However the tag variable value remains “+1” throughout, irrespective of whatever the value feature.[8] is.
How does one deal with simple value changes based on conditional statement in F#?
@John Palmer has your answer, but I’ll add a bit to it…
Note that the reason why your code compiles but does not work as you expect is because the
=operator used in the context oftag = "-1"andtag = "+1"is the equality operator. So those expressions are valid but return aboolvalue. However, you should be receiving the following warning:It would serve you well to heed that warning in your F# coding adventures.
Also note that you can write your algorithm in a purely functional way (without mutable variables) using Seq.fold (among other alternative functional approaches):