F #: partial application and preliminary calculation

Looking at the function in my code today, I wondered if it is possible to combine partial combination and optimization:

let foo (X:float) y1 y2 dx = 
    y1 + (y2 - y1) * dx / X

Basically, just applying the relation - therefore, the first three parameters in one cycle are usually the same.

I thought maybe if I just did this:

let foo2 (X:float) y1 y2 dx = 
    let dy = (y2 - y1) / X
    y1 + dy * dx

F # will become smarter and optimized for me when I partially apply the first three parameters, but in this debugging mode this is not so (although I'm not sure that I started testing it in the correct way).

The question is, should this work? And if not, what is the best way to do this (other than just writing another function with two parameters)?

+5
source share
3 answers

, " " " ", " ".

:

let Expensive x y = 
    printfn "I am a side-effect of Expensive"
    x + y  // imagine something expensive

let F x y z =
    let tmp = Expensive x y
    z + tmp

printfn "Least chance of magic compiler optimization"
for i in 1..3 do    
    F 3 4 i

printfn "Slightly better chance"
let Part = F 3 4
for i in 1..3 do    
    Part i

printfn "Now for real"
let F2 x y =
    let tmp = Expensive x y
    (fun z -> z + tmp)

printfn "Of course this still re-does it"
for i in 1..3 do    
    F2 3 4 i

printfn "Of course this finally saves re-do-ing Expensive"
let Opt = F2 3 4
for i in 1..3 do    
    Opt i

(* output

Least chance of magic compiler optimization
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Slightly better chance
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Now for real
Of course this still re-does it
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Of course this finally saves re-do-ing Expensive
I am a side-effect of Expensive

*)    

, , , "" , .

+4

( , , )

, , , :

let foo3 (X:float) y1 y2 =
    let dy = (y2 - y1) / X
    (fun dx -> y1 + dy * dx)

.

+3

, . N (#time;; F #).

, dx, :

let fdx = foo2 X y1 y2
for dx in dxes do
    fdx dx

, fdx - . .

, ( , , ?) , - 15% ( , , foo2). :

let fdx = foo3 X y1 y2
for dx in dxes do
    fdx dx

foo3 ( Benjlol):

let foo3 (X:float) y1 y2 =
    let dy = (y2 - y1) / X
    (fun dx -> y1 + dy * dx)

, foo3 4 , foo2, , 3 .

+1

All Articles