F#: Not equal/Not operator
While continuing playing with my F# twitter application I was trying to work out how to exclude the tweets that I posted from the list that gets displayed.
I actually originally had the logic the wrong way round so that it was only showing my tweets!
let excludeSelf (statuses:seq<TwitterStatus>) =
statuses |> Seq.filter (fun eachStatus -> eachStatus.User.ScreenName.Equals("markhneedham"))
Coming from the world of Java and C# '!' would be the operator to find the screen names that don’t match my own name. So I tried that.
let excludeSelf (statuses:seq<TwitterStatus>) =
statuses |> Seq.filter (fun eachStatus -> !(eachStatus.User.ScreenName.Equals("markhneedham")))
Which leads to the error:
Type constraint mismatch. The type 'bool' is not compatible with the type 'bool ref'.
If we look at the definition of '!' we see the following:
(!);;
> val it : ('a ref -> 'a)
It’s not a logical negation operator at all. In actual fact it’s an operator used to deference a mutable reference cell.
What I was looking for was actually the 'not' operator.
let excludeSelf (statuses:seq<TwitterStatus>) =
statuses |> Seq.filter (fun eachStatus -> not (eachStatus.User.ScreenName.Equals("markhneedham")))
I could also have used the '<>' operator although that would have changed the implementation slightly:
let excludeSelf (statuses:seq<TwitterStatus>) =
statuses |> Seq.filter (fun eachStatus -> eachStatus.User.ScreenName <> "markhneedham")
The Microsoft Research F# website seems to be quite a useful reference for understanding the different operators.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.