Jérôme MEVEL
Jérôme MEVEL

Reputation: 7822

Function works without passing the parameters

/!\ F# brand newbie /!\

I have this code

#r @"..\packages\Accord.3.4.0\lib\net40\Accord.dll"
#r @"..\packages\Accord.Statistics.3.4.0\lib\net40\Accord.Statistics.dll"
#r @"..\packages\Accord.Math.3.4.0\lib\net40\Accord.Math.dll"

open Accord
open Accord.Statistics.Models.Regression.Linear

let input = [|1,1.;2,2.;3,2.25;4,4.75;5,5.|]

let x = input |> Array.map(fun (x,y) -> float x)
let y = input |> Array.map(fun (x,y) -> y) 
let regression = SimpleLinearRegression()

let sse = regression.Regress(x,y)
let intercept = regression.Intercept
let slope = regression.Slope
let mse = sse/float x.Length
let rmse = sqrt mse
let r2 = regression.CoefficientOfDetermination(x,y)

Which gives me the result

val input : (int * float) [] = [|(1, 1.0); (2, 2.0); (3, 2.25); (4, 4.75); (5, 5.0)|]
val x : float [] = [|1.0; 2.0; 3.0; 4.0; 5.0|]
val y : float [] = [|1.0; 2.0; 2.25; 4.75; 5.0|]
val regression : SimpleLinearRegression = y(x) = 1,075x + -0,224999999999998
val sse : float = 1.06875
val intercept : float = -0.225
val slope : float = 1.075
val mse : float = 0.21375
val rmse : float = 0.4623310502
val r2 : float = 0.9153465347

How is that possible that SimpleLinearRegression function works but we don't even pass it x and y?

Can you point me to a reference to understand what is this F# magic behind that?

Upvotes: 1

Views: 80

Answers (1)

Robert Nielsen
Robert Nielsen

Reputation: 515

I am guessing you are using the F-Sharp Interactive, and sending all of the code to FSI in one swoop.

The magic is that the code is executed first, then the results are written. Even if the sequence of 'val' outputs get a bit counter intuitive that way.

I can illustrate with this example (for future readers):

let mutable a = 1
let f = a <- 2; fun () -> 3
do a <- f ()

which gives this output in FSI:

val mutable a : int = 3
val f : (unit -> int)
val it : unit = ()

notice how a is updated to its final value before being printed (we never even see 1 and 2, even though that are the values of a after line one and two respectively).

Upvotes: 2

Related Questions