Tell HN: F# Rocks

8 points by shawndumas ↗ HN

  type Expr = 
    | Num of int
    | Add of Expr * Expr
    | Mul of Expr * Expr
    | Var of string
 
  let rec Evaluate (env:Map<string,int>) exp = 
  	  match exp with
  	  | Num n -> n
	  | Add (x,y) -> Evaluate env x + Evaluate env y
	  | Mul (x,y) -> Evaluate env x * Evaluate env y
	  | Var id    -> env.[id]

  let envA = Map.ofList [ "a", 1; "b", 2; "c", 3 ]

  let expT1 = Add(Var "a",Mul(Num 2,Var "b"))
  let resT1 = Evaluate envA expT1
=> 5

5 comments

[ 2.8 ms ] story [ 19.9 ms ] thread
Could you care to explain? Right now what I understand is not "F# Rocks" but "F# is the most weird language I've ever seen and no one cares to explain me why I should consider F# as something that rocks" :(
How 'bout this:

  /// Compute the highest-common-factor of two integers
  let rec hcf a b =                       // notice: 2   parameters separated by spaces
	if a=0 then b
	elif a<b then hcf a (b-a)        // elif = else if
	else hcf (a-b) b
	// note: function arguments are usually space separated
	// note: 'let rec' defines a recursive function
Wow, you're pretty sheltered if F# is the weirdest language you've ever seen
The first part defines the "type" of Expr. An Expr can be an int, a variable string, or an Add, Mul of two Exprs. The next bit takes an environment (env) and an Expr (exp) and recursively evaluates sub-Exprs of the Expr. Then an environment is defined, mapping variables to underlying values. Then an expression is defined. Finally, the expression is evaluated in the environment.
It's a simple expression evaluator evaluating a + 2 * b with a = 1 and b = 2. The fun part is that it's all done using only the one recursive Evaluate function with everything else being driven by the type system and pattern matching. The entire program is also strongly typed with only one type declaration (the env argument to Evaluate).

F# is a neat language. I'm sort of surprised he went with the type system rather than computation expressions/async workflows, which are my favorite feature. They aren't unique (they're monads) but the syntax is nice. I'd happily code in F# if I had a reason to write .NET code.