News for hackers. Stuff that matters.

Tell HN: F# Rocks

  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 | 8 points | on HN )
Re:Tell HN: F# Rocks by Khao on Thursday August 04, 2011 @11:25AM (#2846324)
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" :(
Re:Tell HN: F# Rocks by grayrest on Thursday August 04, 2011 @11:47AM (#2846443)
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.

Re:Tell HN: F# Rocks by unignorant on Thursday August 04, 2011 @11:43AM (#2846421)
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.
Re:Tell HN: F# Rocks by shawndumas on Thursday August 04, 2011 @11:35AM (#2846385)
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
Re:Tell HN: F# Rocks by jordandanford on Thursday August 04, 2011 @11:39AM (#2846400)
Wow, you're pretty sheltered if F# is the weirdest language you've ever seen