Wednesday, July 29, 2009

F# Guards are my hero

Previously I mentioned pattern matching which is a nice feature of F#. It is suggested that it is the most powerful feature of F# and I am starting to see why especially in conjunction with Guards.

Continuing my comparrison of F# and Erlang pattern matching erlang also offers guards, but it only has only a few built in guards where as F# you can do whatever you like.

For example

let randomTest = function
| x when (x > 0 && x <> "return value"
|0 -> 0
|x when (x <> "return value"

Granted my example is retarded and simplistic and pointless but hopefully you can see the awesomeness of being able to give whatever you want in the guard clause.

Also the cause doesn't need to be built in functions it could be something like

|x when (x > 0 && (someFunction x) == true) -> "return value"

The downside.

Erlang only offers a small set of built in guards because that way they can guarentee they will terminate but in F# since the programmer can define his own guard clauses, who knows, if they make a mistake the function may never terminate.

So F# gives a decent amount of control over patterns but no promise of relability

1 comment:

  1. Try making a guard clause that goes into an infinite loop and watch the compiler's antics :)

    ReplyDelete