· f

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.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket