F# Power issues which accepts both arguments to be bigints - f#

I am currently experimenting with F#. The articles found on the internet are helpful, but as a C# programmer, I sometimes run into situations where I thought my solution would help, but it did not or just partially helped.
So my lack of knowledge of F# (and most likely, how the compiler works) is probably the reason why I am totally flabbergasted sometimes.
For example, I wrote a C# program to determine perfect numbers. It uses the known form of Euclids proof, that a perfect number can be formed from a Mersenne Prime 2p−1(2p−1) (where 2p-1 is a prime, and p is denoted as the power of).
Since the help of F# states that '**' can be used to calculate a power, but uses floating points, I tried to create a simple function with a bitshift operator (<<<) (note that I've edit this code for pointing out the need):
let PowBitShift (y:int32) = 1 <<< y;;
However, when running a test, and looking for performance improvements, I also tried a form which I remember from using Miranda (a functional programming language also), which uses recursion and a pattern matcher to calculate the power. The main benefit is that I can use the variable y as a 64-bit Integer, which is not possible with the standard bitshift operator.
let rec Pow (x : int64) (y : int64) =
match y with
| 0L -> 1L
| y -> x * Pow x (y - 1L);;
It turns out that this function is actually faster, but I cannot (yet) understand the reason why. Perhaps it is a less intellectual question, but I am still curious.
The seconds question then would be, that when calculating perfect numbers, you run into the fact that the int64 cannot display the big numbers crossing after finding the 9th perfectnumber (which is formed from the power of 31). I am trying to find out if you can use the BigInteger object (or bigint type) then, but here my knowledge of F# is blocking me a bit. Is it possible to create a powerfunction which accepts both arguments to be bigints?
I currently have this:
let rec PowBigInt (x : bigint) (y : bigint) =
match y with
| bigint.Zero -> 1I
| y -> x * Pow x (y - 1I);;
But it throws an error that bigint.Zero is not defined. So I am doing something wrong there as well. 0I is not accepted as a replacement, since it gives this error:
Non-primitive numeric literal constants cannot be used in pattern matches because they
can be mapped to multiple different types through the use of a NumericLiteral module.
Consider using replacing with a variable, and use 'when <variable> = <constant>' at the
end of the match clause.
But a pattern matcher cannot use a 'when' statement. Is there another solution to do this?
Thanks in advance, and please forgive my long post. I am only trying to express my 'challenges' as clear as I can.

I failed to understand why you need y to be an int64 or a bigint. According to this link, the biggest known Mersenne number is the one with p = 43112609, where p is indeed inside the range of int.
Having y as an integer, you can use the standard operator pown : ^T -> int -> ^T instead because:
let Pow (x : int64) y = pown x y
let PowBigInt (x: bigint) y = pown x y
Regarding your question of pattern matching bigint, the error message indicates quite clearly that you can use pattern matching via when guards:
let rec PowBigInt x y =
match y with
| _ when y = 0I -> 1I
| _ -> x * PowBigInt x (y - 1I)

I think the easiest way to define PowBigInt is to use if instead of pattern matching:
let rec PowBigInt (x : bigint) (y : bigint) =
if y = 0I then 1I
else x * PowBigInt x (y - 1I)
The problem is that bigint.Zero is a static property that returns the value, but patterns can only contain (constant) literals or F# active patterns. They can't directly contain property (or other) calls. However, you can write additional constraints in where clause if you still prefer match:
let rec PowBigInt (x : bigint) (y : bigint) =
match y with
| y when y = bigint.Zero -> 1I
| y -> x * PowBigInt x (y - 1I)
As a side-note, you can probably make the function more efficent using tail-recursion (the idea is that if a function makes recursive call as the last thing, then it can be compiled more efficiently):
let PowBigInt (x : bigint) (y : bigint) =
// Recursive helper function that stores the result calculated so far
// in 'acc' and recursively loops until 'y = 0I'
let rec PowBigIntHelper (y : bigint) (acc : bigint) =
if y = 0I then acc
else PowBigIntHelper (y - 1I) (x * acc)
// Start with the given value of 'y' and '1I' as the result so far
PowBigIntHelper y 1I
Regarding the PowBitShift function - I'm not sure why it is slower, but it definitely doesn't do what you need. Using bit shifting to implement power only works when the base is 2.

You don't need to create the Pow function.
The (**) operator has an overload for bigint -> int -> bigint.
Only the second parameter should be an integer, but I don't think that's a problem for your case.
Just try
bigint 10 ** 32 ;;
val it : System.Numerics.BigInteger =
100000000000000000000000000000000 {IsEven = true;
IsOne = false;
IsPowerOfTwo = false;
IsZero = false;
Sign = 1;}

Another option is to inline your function so it works with all numeric types (that support the required operators: (*), (-), get_One, and get_Zero).
let rec inline PowBigInt (x:^a) (y:^a) : ^a =
let zero = LanguagePrimitives.GenericZero
let one = LanguagePrimitives.GenericOne
if y = zero then one
else x * PowBigInt x (y - one)
let x = PowBigInt 10 32 //int
let y = PowBigInt 10I 32I //bigint
let z = PowBigInt 10.0 32.0 //float
I'd probably recommend making it tail-recursive, as Tomas suggested.

Related

Definition style preferences

What is the preferable style for F# definitions?
The book I am studying makes regular use the following style:
let foo = fun x y ->
let aux1 = fun z -> z * 2
in aux1 x +
let aux2 = fun q -> q * 3
in aux2 y;;
On the other side, when I look for information on the web, it is most likely to meet something like:
let foo (x: int) (y: int) =
let aux1 (z:int) = z * 2
in aux1 x +
let aux2 (q: int) = q * 3
in aux2 y;;
On the Guide I failed to find a reference about it. Is it a matter that goes beyond "mere style"? There are efficiency implications behind these two approaches?
What does your experience suggest?
As a general rule, F# function definitions tend to do one of two things:
Define as few types as possible (let foo x y = ...). This is the case for most functions. Or...
Explicitly define the types of each argument and the return type (let foo (x : int) (y : int) : int = ....
Style #2 is rare, and I've usually seen it for functions that are explicitly part of the API of a module, and that have /// comments to provide documentation as well. For internal functions, though, the typeless variant is usually used, since F#'s type inference works so well.
Also, as s952163 pointed out in a comment, the in keyword is almost never used anymore, since the #light style makes it unnecessary. I'd expect to see your sample code written as follows in modern F# style:
let foo x y =
let aux1 z = z * 2
let aux2 q = q * 3
(aux1 x) + (aux2 y)
No ;; necessary, either, unless you're typing into the F# Interactive console. If you're using VS Code + Ionide, and highlighting segments of code and pressing Alt + Enter to send them to F# Interactive, then you don't need any ;; separators because Ionide adds them automatically.
I found evidence suggesting that the first style, even if today unconventional, is intrinsically connected to currying and anonymous functions.
Currying is a powerful characteristic of F#, where, I remember, every function could take only one parameter. For example:
let add x y = x + y
val add: int -> int -> int
The signature is interpreted as add is a function that takes two integers as input and return an integer.
When compile time comes, the function is interpreted like:
let add2 = fun x -> fun y -> x + y
val add2: int -> int -> int
where val add2: int -> int -> int is semantically equivalent to val add: (int -> (int -> int))
By providing an argument to add2, such as 6, it returns fun y -> 6 + y, which is another function waiting for its argument, while x is replaced by 6.
Currying means that every argument actually returns a separate function: that's why when we call a function with only few of its parameters returns another function.
If I got it correctly, the more common F# syntax of the second example, let add x y = x + y, could be thought like syntactic sugar for the explicit currying style shown above.

What's the meaning of the `in` keyword in this example (F#)

I've been trying to get my head round various bits of F# (I'm coming from more of a C# background), and parsers interest me, so I jumped at this blog post about F# parser combinators:
http://santialbo.com/blog/2013/03/24/introduction-to-parser-combinators
One of the samples here was this:
/// If the stream starts with c, returns Success, otherwise returns Failure
let CharParser (c: char) : Parser<char> =
let p stream =
match stream with
| x::xs when x = c -> Success(x, xs)
| _ -> Failure
in p //what does this mean?
However, one of the things that confused me about this code was the in p statement. I looked up the in keyword in the MSDN docs:
http://msdn.microsoft.com/en-us/library/dd233249.aspx
I also spotted this earlier question:
Meaning of keyword "in" in F#
Neither of those seemed to be the same usage. The only thing that seems to fit is that this is a pipelining construct.
The let x = ... in expr allows you to declare a binding for some variable x which can then be used in expr.
In this case p is a function which takes an argument stream and then returns either Success or Failure depending on the result of the match, and this function is returned by the CharParser function.
The F# light syntax automatically nests let .. in bindings, so for example
let x = 1
let y = x + 2
y * z
is the same as
let x = 1 in
let y = x + 2 in
y * z
Therefore, the in is not needed here and the function could have been written simply as
let CharParser (c: char) : Parser<char> =
let p stream =
match stream with
| x::xs when x = c -> Success(x, xs)
| _ -> Failure
p
The answer from Lee explains the problem. In F#, the in keyword is heritage from earlier functional languages that inspired F# and required it - namely from ML and OCaml.
It might be worth adding that there is just one situation in F# where you still need in - that is, when you want to write let followed by an expression on a single line. For example:
let a = 10
if (let x = a * a in x = 100) then printfn "Ok"
This is a bit funky coding style and I would not normally use it, but you do need in if you want to write it like this. You can always split that to multiple lines though:
let a = 10
if ( let x = a * a
x = 100 ) then printfn "Ok"

Value or constructor is not defined

I'm learning f# and I've got a pretty trivial problem that doesn't seem to make sense. I'm working on Project Euler problem 2 and I've got this:
let fib (x : BigInteger) (y : BigInteger) (max : BigInteger) =
let added = x + y
if added > max then y
else fib y (x + y) max
I've got the error at the recursive fib call:
Value or constructor 'fib' is not defined
And I'm not sure why. Any help?
Because fib is recursive function, it has to start with let rec.
In F#, if you want to write a recursive function, you have to use the rec keyword:
let rec fib (x : BigInteger) (y : BigInteger) (max : BigInteger) =
let added = x + y
if added > max then y
else fib y (x + y) max
That's because in F# under normal circumstances, you can only use identifiers declared before the current code, unlike in C#.
Talking of Project Euler Problem 2, you may consider instead of recursion going with Seq.unfold, which is very idiomatic and gives you all Fibonacci numbers at once:
let fibs = Seq.unfold (fun (current, next) ->
Some(current, (next, current + next))) (1,2)
Now fibs represents lazy sequence of Fibonacci numbers :
>fibs;;
val it : seq<int> = seq[1; 2; 3; 5; ...]
And to make it of BigInteger just substitute (1,2) by (1I,2I), although the solution allows you to stay within ordinary integers.

Function returning function and not float in f#

Sorry for the really bad title, but I couldn't come up with a better one...
I am following Structure and interpretation of computer programs and am trying to do the example from section 1.1.7 about Netwon's method of seccessive approximation for finding square roots.
I try to implement it in F# and i believe I'm pretty close to getting there, but probably There is some kind of syntactic problem.
Here is my code (I used linqpad, hence the Dump()), below follows the question
let square a = a * a
let average a b = (a + b)/2.0
let a = average 2.0 1.0
a.Dump()
let improve guess x = average guess x
let i = improve 2.0 1.0
i.Dump()
let goodEnough guess x = abs (x - square(guess)) < 0.001
let g = goodEnough 3.0 4.0
g.Dump()
let g2 = goodEnough 2.0 4.0
g2.Dump()
let rec sqrtIterator guess x =
if goodEnough guess x then guess
else sqrtIterator(improve(guess x) x)
let sqrt x = sqrtIterator 1.0 x
I get an error on the recursive call to sqrtIterator saying:
This expression was expected to have type float but here has type float -> float.
So it seems I am missing a parameter making it return a function taking one parameter, but I can not see whats wrong?
Changing sqrtIterator(improve(guess x) x) to sqrtIterator (improve guess x) x would solve the problem.
From the first part of the expression in sqrtIterator:
if goodEnough guess x then guess
the type checker knows that guess is a float since goodEnough has already had type float -> float.
The else branch is expected to has type float as well. Consequently, sqrtIterator has type float -> float -> float.
However, you provided sqrtIterator(improve(guess x) x) in the else branch. The outermost parentheses indicate that improve(guess x) x is a single parameter which supposes to be a float.
Now sqrtIterator(improve(guess x) x) returns float -> float hence the above error message.
Here is the problem fixed:
let rec sqrtIterator guess x =
if goodEnough guess x then guess
else sqrtIterator (improve guess x) x
Your parens were wrong.
Your bracketing in sqrtIterator is slightly off - you need
else sqrtIterator (improve guess x) x

Reverse currying?

I'd like to compose functions in a certain way. Please consider these 2 functions in pseudocode (not F#)
F1 = x + y
F2 = F1 * 10 // note I did not specify arguments for F1, 'reverse curry' for lack of a better word
What I would like for F# to do is figure out that since
let F1 x y = x + y
//val F1 : int -> int -> int
the code let F2 = F1 * 10 would give me the same signature as F1: val F2 : int -> int -> int, and calling F2 2 3 would result in 50: (2 + 3) * 10. That would be rather clever...
What happens is quite different tho. The first line goes as expected:
let F1 x y = x + y
//val F1 : int -> int -> int
but when I add a second line let F2 = F1 * 10 it throws off F#. It complains that the type int does not match the type 'a -> 'b -> 'c and that F1 now requires member ( + ).
I could of course spell it out like this:
let F1(x, y) = x + y
let F2(x, y) = F1(x, y) * 10
But now I might as well have used C#, we're not that far away anymore. The tupled arguments break a lot of the elegance of F#. Also my real functions F1 and F2 have a lot more arguments than just 2, so this makes me go cross eyed, exactly what I wanted to dodge by using F#. Saying it like this would be much more natural:
let F1 x y = x + y
let F2 = F1 * 10
Is there any way I can (almost) do that?
For extra credits: what exactly goes on with these error messages? Why does the second line let F2 = F1 * 10 change the typing on the first?
Thanks in advance for your thoughts,
Gert-Jan
update
Two apporaches that (almost) do what's described.
One using a tuple. Second line looks a little quirky a first, works fine. Small drawback is I can't use currying now or I'll have to add even more quirky code.
let F1 (a, b) = a + b
let F2 = F1 >> (*) 10
F2(2, 3) // returns 50
Another approach is using a record. That is a little more straight forward and easier to get at first glance, but requieres more code and ceremony. Does remove some of the elegance of F#, looks more like C#.
type Arg (a, b) =
member this.A = a
member this.B = b
let F1 (a:Arg) = a.A + a.B
let F2 (a:Arg) = F1(a) * 10
F2 (Arg(2, 3)) // returns 50
There is no pattern for this in general. Using combinators (like curry and uncurry) as suggested by larsmans is one option, but I think the result is less readable and longer than the explicit version.
If you use this particular pattern often, you could define an operator for multiplying a function (with two parameters) by a scalar:
let ( ** ) f x = fun a b -> (f a b) * x
let F1 x y = x + y
let F2 = F1 ** 10
Unfortunately, you cannot add implementation of standard numeric operators (*, etc.) to existing types (such as 'a -> 'b -> int). However, this is quite frequent request (and it would be useful for other things). Alternatively, you could wrap the function into some object that provides overloaded numeric operators (and contains some Invoke method for running the function).
I think an appropriate name for this would be lifting - you're lifting the * operator (working on integers) to a version that works on functions returning integers. It is similar to lifting that is done in the C# compiler when you use * to work with nullable types.
To explain the error message - It complains about the expression F1 * 10:
error FS0001: The type 'int' does not match the type ''a -> 'b -> 'c'
I think it means that the compiler is trying to find an instantiation for the * operator. From the right-hand side, it figures out that this should be int, so it thinks that the left-hand side should also be int - but it is actually a function of two arguments - something like 'a -> 'b -> c'.
That would be rather clever...
So clever that it would beat the hell out of the type system. What you want is array programming as in APL.
Is there any way I can (almost) do that?
I don't speak F#, but in Haskell, you'd uncurry F1, then compose with *10, then curry:
f2 = curry ((*10) . uncurry f1)
Which in an ML dialect such as F# becomes something like:
let curry f x y = f (x,y)
let uncurry f (x,y) = f x y
let mult x y = x * y
let F1 x y = x + y
let F2 = curry (uncurry F1 >> mult 10)
(I wasn't sure if curry and uncurry are in the F# standard library, so I defined them. There may also be a prettier way of doing partial application of * without defining mult.)
BTW, using point-free (or rather pointless in this case) approach one could define these functions in the following way:
let F1 = (+)
let F2 = (<<)((*)10) << F1

Resources