Definition style preferences - f#

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.

Related

How to invoke function using named parameter arguments in F#

How can I call F# functions by specifying the parameter names in the call site?
I've tried the following:
let add x y =
x + y
add (x = 10) (y = 10) // How to specify the name x and y when calling add?
But it gives this error:
error FS0039: The value or constructor 'x' is not defined.
You can't invoke let-bound functions with named arguments. It's allowed only for methods in classes
Named arguments are allowed only for methods, not for let-bound functions, function values, or lambda expressions.
Documentation
Technically you can declare static class and use method from it, but I think it's wrong. Just wrong. Don't do it
[<AbstractClass; Sealed>]
type MathOperations =
static member Add (x, y) = x + y
open type MathOperations
[<EntryPoint>]
let main argv =
Add(x = 3, y = 4)
|> printfn "%d"
0
This issue confused me too in the beginning. Functions and methods are not alike.
Functions are curried by default to support partial application. They don't support named argument calls.
Methods support named arguments using a single tuple for all parameters.
(EDIT after Bent Tranberg's comment) Methods also support curried declaration member _.Add x y = x + y and even mixed style declaration member _.Add3 (x: int, y: int) (z: int) = x + y + z but these methods cannot be called using named arguments o.Add3 (y=2, x=1) 3 💥
In JavaScript, named arguments can be simulated using an object literal as argument. Let's try do the same in F#, using tuple or record:
1. Tuple: Method arguments are provided all at once with a tuple. Can we use a tuple as function parameter and call the function with named arguments? No ❌
let add (x, y) = x + y
add (x = 1, y = 2) // 💥
// ~ Error FS0039: The value or constructor 'x' is not defined
2. Anonymous record: not possible due to actual limitation in anonymous record deconstruction ❌
let add {| X = x; Y = y |} = x + y
// ~~ Error FS0010: Unexpected symbol '{|' in pattern
3. Named record: ⚠️
type AddParam = { x: int; y: int }
let add { x = x; y = y } = x + y
add { x = 1; y = 2 }
This way, we are able to name the arguments and choose their order ({ y = 2; x = 1 } but we loose the partial application. So it's not idiomatic→ should be avoided, unless in specific cases.
4. Single-case DU: 👌
If we care only about the argument naming but not about the argument re-ordering, we can use discriminated unions, especially single-case DU:
type XParam = X of int
type YParam = Y of int
let add (X x) (Y y) = x + y
add (X 1) (Y 2)
This way, the arguments appeared as named and partial application is preserved.
--
EDIT
☝ I don't recommend creating single-case DU just to simulate named arguments ! It's the other way around: when we have single-case DU in our domain model, we know that they will bring their semantic to document the code and help reasoning about the code, in this case more or less like named arguments.
You have to understand function calling in F#, which is different from traditional imperative languages like C#.
let f x y = x + y // defines a function with this signature:
val f : x:int -> y:int -> int
// this function is full or partially applicable:
let g = f 4 // partial application
val g : (int -> int) // a new function that evaluates f 4 y
g 10
val it : int = 14
In traditional languages functions have a single set of arguments. In F# you express such traditional functions with multiple arguments into a function with a tuple argument:
let f (x, y) = x + y
val f : x:int * y:int -> int
// partial application is no longer possible, since the arguments have been packed into a single tuple
Such traditional tuple-argument functions do not allow calls with named arguments:
f (x=3, y=5) // interpreted as = test expressions
F# language design is sound here, and (x=3, y=5) does not express the desired tuple.
F# has named arguments since a while (this was added in the last years sometime). This is limited to member functions however. Once you translate your function into a member it works:
type A() =
static member f (x,y) = x + y
A.f(y=3, x=4) // yes, this works!

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"

Exception handling in point-free functions

I'm stuck with a seemingly trivial problem: I'm unable to handle an exception in a function if it's written in a point-free manner.
Consider these two functions:
let divide1 x y =
try
x / y
with
| :? System.DivideByZeroException -> 42
let divide2 =
try
(/)
with
| :? System.DivideByZeroException -> fun _ _ -> 42
let x1 = divide1 5 0 // works fine
let x2 = divide2 5 0 // doesn't handle an exception
Although both functions are seemingly same, they have different types:
val divide1: int -> int -> int
val divide2: (int -> int -> int)
Obviously, divide2 does not even attempt to handle an exception. It simply returns an operator.
What can I do in order to make divide2 handle the exception in a proper manner (except specifically declaring its arguments)?
This is one of the reasons why I find the point-free style problematic. It makes it difficult to use standard language constructs like try .. with (or standard loops and other F# features) and you need to replace them with custom combinators. In this case, you could define combinator tryWith2 that wraps a two-argument function in an exception handler:
let tryWith2 f h a b =
try f a b // Call the function with two arguments
with e ->
// Try running the error handler with the exception
match h e with
| Some g -> g a b // Error handler provided another function
| _ -> reraise() // Error was not handled - reraise
Then you could write the function in a point-free style like this (the error handling is still not-point-free, but I do not want to make this too silly :-))
let divide2 =
tryWith2 (/) (function
| :? System.DivideByZeroException -> Some(fun _ _ -> 42)
| _ -> None)
let x1 = divide2 5 0 // returns 42
let x2 = divide2 5 1 // returns 5
Of course, the point free style is useful, even in F#. For example, when writing a DSL, it is a great way to compose declarative specification (because the primitives express something using higher-level of abstraction). Here, you need to express something that is quite close to normal F# code and, I believe, that is best expressed as normal F# code.
What you need to remember is that in divide2, you aren't returning the result of X divided by Y, you're returning a function that divides X by Y. The code for the let binding is being executed immediately because it isn't given function syntax. Let's look at both divide bindings with the longer function syntax:
let divide1 =
fun x ->
fun y ->
try
x / y
with
| :? System.DivideByZeroException -> 42
let divide2 =
try
fun x ->
fun y ->
x / y
with
| :? System.DivideByZeroException -> fun _ _ -> 42
When displayed this way, it should be clearer how the two definitions are different. The try block is in a completely different location, and executed at different points in time.
The only way to add logic such as exception handling to an existing function is to wrap it, either as you do in divide1, or with a higher order function as Tomas has shown.

F# Power issues which accepts both arguments to be bigints

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.

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