List Info

Thread: "ocaml_beginners"::[] What does this do?




"ocaml_beginners"::[] What does this do?
country flaguser name
United States
2007-02-25 19:09:07

Folks,

I don't understand the use of "function" in the following chunk of
code. Could someone explain it to me please? Does the code define
variance as a function of one argument?

let variance =
let aux (m_k, s_k, k) x_k =
let m_k2 = m_k +. (x_k -. m_k) /. k in
(m_k2, s_k +. (x_k -. m_k) *. (x_k -. m_k2), k +. 1.) in
function [] -> invalid_arg "variance" | x1::t ->
let (_, s, n2) = List.fold_left aux (x1, 0., 2.) t in
s /. (n2 -. 2.);;

Thanks, Joel

--
http://wagerlabs.com/

__._,_.___
.

__,_._,___
RE: "ocaml_beginners"::[] What does this do?
country flaguser name
United States
2007-02-25 19:28:13

The "function" keyword creates a function that takes one parameter and
automatically pattern matches against it. It's the same as:

Fun x -> match x with

.

So yeah, variance ends up being a function that accepts a list, if it's
empty you get an exception, and if its not it calculates the variance

_____

From: ocaml_beginners%40yahoogroups.com">ocaml_beginnersyahoogroups.com
[mailto: ocaml_beginners%40yahoogroups.com">ocaml_beginnersyahoogroups.com] On Behalf Of Joel Reymont
Sent: Sunday, February 25, 2007 8:09 PM
To: ocaml_beginners%40yahoogroups.com">ocaml_beginnersyahoogroups.com
Subject: "ocaml_beginners"::[] What does this do?

Folks,

I don't understand the use of "function" in the following chunk of
code. Could someone explain it to me please? Does the code define
variance as a function of one argument?

let variance =
let aux (m_k, s_k, k) x_k =
let m_k2 = m_k +. (x_k -. m_k) /. k in
(m_k2, s_k +. (x_k -. m_k) *. (x_k -. m_k2), k +. 1.) in
function [] -> invalid_arg "variance" | x1::t ->
let (_, s, n2) = List.fold_left aux (x1, 0., 2.) t in
s /. (n2 -. 2.);;

Thanks, Joel

--
http://wagerlabs. <http://wagerlabs.com/> com/

[Non-text portions of this message have been removed]

__._,_.___
.

__,_._,___
Re: "ocaml_beginners"::[] What does this do?
country flaguser name
United States
2007-02-25 19:30:12

On Mon, 26 Feb 2007, Joel Reymont wrote:

> Folks,
&gt;
> I don't understand the use of "function" in the following chunk of
> code. Could someone explain it to me please? Does the code define
&gt; variance as a function of one argument?

Yes.

function p1 -> e1 | p2 -> e2 | ...

(where p1 and p2 are patterns and e1 and e2 are expressions)
is a shortcut for

fun x -> match x with p1 -> e1 | p2 -> e2 | ...

Martin

--
Martin Jambon
http://martin.jambon.free.fr

__._,_.___
.

__,_._,___
[1-3]

about | contact  Other archives ( Real Estate discussion Medical topics )