miércoles, 13 de abril de 2011

1.1.6 defining a procedure that computes the absolute value of a number


Section 1.1.6 of SICP presents the math rule
"absolute value of a number".SICP present
a couple of implementations of it, both using 
case analysis with cond and if-boolean branching.
This exercise should be a case of pattern
matching.I like F# pattern matching a lot.Unlike 
other functional concepts,(e.g: Curried functions)
hadn't any problem understanding matching.
Certainly it's a powerful tool. You can
think of keyword match Foo with as C#'s swich 
statement done the right way.

let abs x =
   match x with
    | x when x > 0 -> x       //match only when x > 0
    | x when x = 0 -> 0       //match only when x = 0
    | x when x < 0 -> (-x)    //match only when x < 0
    ;;

To test it evaluate the following expresions with REPL

let  absTestA = abs -3
let  absTestB = abs  5
let  absTestC = abs  0

And REPL will return:

 val absTestA : int = 3
 val absTestB : int = 5
 val absTestC : int = 0


No hay comentarios:

Publicar un comentario