42 people like it.

inline pow

LanguagePrimitives help create inline functions

Tail recursive version

1: 
2: 
3: 
4: 
5: 
let inline pow b e =
    let rec loop acc = function
    | e when e < LanguagePrimitives.GenericOne<_> -> acc
    | e -> loop (b*acc) (e-LanguagePrimitives.GenericOne<_>)
    loop LanguagePrimitives.GenericOne e

Original version

1: 
2: 
3: 
4: 
5: 
let inline pow_ b e =
    let rec loop = function
    | e when e < LanguagePrimitives.GenericOne<_> -> LanguagePrimitives.GenericOne<_>
    | e -> b * (loop (e-LanguagePrimitives.GenericOne<_>))
    loop e

console output

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
(*
val inline pow :
   ^a ->  ^c ->  ^b
    when ( ^a or  ^b) : (static member ( * ) :  ^a *  ^b ->  ^b) and
          ^b : (static member get_One : ->  ^b) and
          ^c : (static member get_One : ->  ^c) and  ^c : comparison and
         ( ^c or  ^d) : (static member ( - ) :  ^c *  ^d ->  ^c) and
          ^d : (static member get_One : ->  ^d)

> pow 5 2;;
val it : int = 25
> pow 5.0 2;;
val it : float = 25.0
> *)
val pow : b:'a -> e:'c -> 'b (requires member ( * ) and member get_One and member get_One and comparison and member ( - ) and member get_One)

Full name: Script.pow
val b : 'a (requires member ( * ) and member get_One)
val e : 'c (requires member get_One and comparison and member ( - ) and member get_One)
val loop : ('b -> 'c -> 'b) (requires member get_One and member ( * ) and member get_One and comparison and member ( - ) and member get_One)
val acc : 'b (requires member get_One and member ( * ))
module LanguagePrimitives

from Microsoft.FSharp.Core
val GenericOne<'T (requires member get_One)> : 'T (requires member get_One)

Full name: Microsoft.FSharp.Core.LanguagePrimitives.GenericOne
val pow_ : b:'a -> e:'c -> 'b (requires member ( * ) and member get_One and member get_One and comparison and member ( - ) and member get_One)

Full name: Script.pow_
val loop : ('c -> 'b) (requires member get_One and comparison and member ( - ) and member get_One and member get_One and member ( * ))

More information

Link:http://fssnip.net/1v
Posted:6 years ago
Author:Dmitri Pavlenkov
Tags: inline , languageprimitives , pow