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.
Related
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.
I'm currently working on a project where I have to create a lot of functions according to some rules and reuse those functions later. And for that I started to learn F#, just seemed to be a more natural thing to do in F# than in C#.
I managed to create the functions as they should be but I have some problems whith reusing them. Below is a very simplified example, to show what I'm trying to do.
let choice = 2
let fCreator (x:float) =
match choice with
|1 -> x * x
|2 -> x * 10.0
|3 -> x + 20.0
|_ -> x
I have a global variable choice according to which in fCreator a transformation of x is selected and returned. This works fine by calling it e.g.
let result1 = fCreator 1.0
But the problem is that I have to use the selected transformation (in that case x*10) for a lot different inputs and when using it this way
let result2 = fCreator 2.0
let result3 = fCreator 3.0
.
.
.
then the whole selection process is done again, which is no big deal here but my actual selection function is a far more complicated one and takes some time to compute.
Is it possible to call fCreator, get and save the selected transformation and then directly use it? Something like
let selectedFunction x:float = fCreator x:float
where then
selectedFunction x:float = x * 10
is
I know the above wont work that way, but I hope you get the idea what I'm trying to do. selectedFunction then should be the chosen transformation from fCreator.
I'm quite new to F# so I might be overlooking something obvious but I perused several Q&As according to function caching in F#. But as far as I can see neither memoizing nor lazy evaluation will do what I'm looking for.
I also tried to write fCreator as a void function with x in the body as a declared but not initialized variable and then returning a transformation with that variable. But it didn't quite work out and is as much as I know also not the proper way to do in F#.
I hope that someone could give me a hint here.
Instead of relying on a global value, define a function that returns another function:
let selectCreator choice =
match choice with
| 1 -> fun x -> x * x
| 2 -> fun x -> x * 10.0
| 3 -> fun x -> x + 20.0
| _ -> id
This is a function that returns the desired function. It has the signature int -> (float -> float). You can bind it to a particular choice like this:
let creator = selectCreator 2
You can now use creator with various values:
> creator 2.0;;
val it : float = 20.0
> creator 3.0;;
val it : float = 30.0
The selection only happens when you invoke selectCreator; every time you call creator, you simply call the returned function. This can be illustrated by making the following modification to selectCreator:
let selectCreator choice =
match choice with
| 1 ->
printf "1 selected"
fun x -> x * x
| 2 ->
printf "2 selected"
fun x -> x * 10.0
| 3 ->
printf "3 selected"
fun x -> x + 20.0
| _ ->
printf "Default selected"
id
Although in Functional Programming, we dislike side-effects, it's a great way to demonstrate that this works as intended. Here's a log of an FSI session:
> let creator = selectCreator 2;;
2 selected
val creator : (float -> float)
> creator 4.0;;
val it : float = 40.0
> creator 5.0;;
val it : float = 50.0
Notice that it only prints out the selection when creator is selected, not when it's invoked.
This approach also has the advantage that you change your mind at run-time, and select a different function:
> let creator3 = selectCreator 3;;
3 selected
val creator3 : (float -> float)
> creator3 4.0;;
val it : float = 24.0
> creator3 5.0;;
val it : float = 25.0
If the choice is computed once and then always the same, then you can do something like this:
let choice = 2
let fCreator =
match choice with
| 1 -> fun x -> x * x
| 2 -> fun x -> x * 10
| 3 -> fun x -> x + 20
| _ -> x
This will return a whole different function depending on the value of choice.
You have the right idea, reusing a function "returned from another one". You can do it like this:
let mkCreator choice = function
| 1 -> fun x -> x * x
| 2 -> ( *) 10.0
| 3 -> (+) 20.0
| _ -> id
let fCreator = mkCreator 2
fCreator 20.0 (* val it = 200.0 : float *)
This makes the "expensive" mkCreator call happen only once.
Another answer suggested the following:
let mkCreator choice x = function
| 1 -> x * x
| 2 -> (*) 10.0
| 3 -> (+) 20.0
| _ -> x
let fCreator = mkCreator 2
However, the body of mkCreator won't be evaluated until it has all of it's arguments. That means that every time you subsequently apply fCreator, you will evaluate the body of mkCreator. But this was exactly what we were trying to avoid!
Thank you all very much for your responses!
So the overall idea is to use anonymous functions as return values in my selection function. This works perfectly fine and is a simple way to do in the above examples.
But the problem is (at least for me) that in my actual selection function the transformations are created through lots of recursive function calls, which makes it not that easy to define them as anonymous functions. The created transformations (like e.g. x*x above) then are actually sequences of operations and recursive functions and best thing would have been to let them unchanged.
I hoped it might be possible to store the selected transformation only by changing the code that calls the selection function. So that I could get something like the creator function in Mark's example, but keeping the return values in selectCreator as they are in my original example (not as anonymous functions).
I have googlet a bit, and I haven't found what I was looking for. As expected. My question is, is it possible to define a F# pipeline placeholder? What I want is something like _ in the following:
let func a b c = 2*a + 3*b + c
2 |> func 5 _ 6
Which would evaluate to 22 (2*5 + 3*2 + 6).
For comparison, check out the magrittr R package: https://github.com/smbache/magrittr
This is (unfortunately!) not supported in the F# language - while you can come up with various fancy functions and operators to emulate the behavior, I think it is usually just easier to refactor your code so that the call is outside of the pipeline. Then you can write:
let input = 2
let result = func 5 input 6
The strength of a pipeline is when you have one "main" data structure that is processed through a sequence of steps (like list processed through a sequence of List.xyz functions). In that case, pipeline makes the code nicer and readable.
However, if you have function that takes multiple inputs and no "main" input (last argument that would work with pipelines), then it is actually more readable to use a temporary variable and ordinary function calls.
I don't think that's possible, but you could simply use a lambda expression, like
2 |> (fun b -> func 5 b 6)
Here's a point-free approach:
let func a b c = 2*a + 3*b + c
let func' = func 5 >> (|>) 6
let result = 2 |> func'
// result = 22
I have explained it in details here.
Be aware, however, that someone who would work with your code will not quickly grasp your intent. You may use it for purposes of learning the deeper aspects of the language, but in real-world projects you will probably find a straightforward approach suitable better:
let func' b = func 5 b 6
You could use a new function like that:
let func a b c = 2*a + 3*b + c
let func2 b = func 5 b 6
2 |> func2
#Dominic Kexel's right on the money. If the object isn't really the placement of a placeholder in the chain of arguments, which could have been achieved by a lambda function, but changing their order, then it's more a case of flip than pipe.
From the simple two-argument case
let flip f b a = f a b
// val flip : f:('a -> 'b -> 'c) -> b:'b -> a:'a -> 'c
we need to derive a function
let flip23of3 f a c b = f a b c
// val flip23of3 : f:('a -> 'b -> 'c -> 'd) -> a:'a -> c:'c -> b:'b -> 'd
in order to flip the second and third argument. This could have also been written
let flip23of3' f = f >> flip
let func a b c = 2*a + 3*b + c
2 |> flip23of3 func 5 6
// val it : int = 22
I have given it a try myself. The result is not perfect, but it is as close as I have gotten:
let (|.|) (x: 'a -> 'b -> 'c) (y: 'b) = fun (a: 'a) -> x a y
let func (a:string) b (c:int) = 2.*(float a) + b + 5.*(float c)
let foo = func "4" 9. 5
printfn "First: %f" foo
let bar =
"4"
|> ((func |.| 9.) |.| 5)
printfn "Second: %f" bar
let baz =
9.
|> (func "4" |.| 5)
printfn "Third: %f" baz
The output is, as expected
First: 42.000000
Second: 42.000000
Third: 42.000000
I'd like to check that a value is of a particular case of a discriminated union, without having to also check any included data. My motivation is to only test one thing with each unit test.
An example is as follows (the last two lines give compilation errors):
module MyState
open NUnit.Framework
open FsUnit
type MyState =
| StateOne of int
| StateTwo of int
let increment state =
match state with
| StateOne n when n = 10 -> StateTwo 0
| StateOne n -> StateOne (n + 1)
| StateTwo n -> StateTwo (n + 1)
[<Test>]
let ``incrementing StateOne 10 produces a StateTwo`` ()=
let state = StateOne 10
(increment state) |> should equal (StateTwo 0) // works fine
(increment state) |> should equal (StateTwo _) // I would like to write this...
(increment state) |> should be instanceOfType<StateTwo> // ...or this
Can this be done in FsUnit?
I'm aware of this answer but would prefer not to have to write matching functions for each case (in my real code there are far more than two).
If you don't mind using reflections, the isUnionCase function from this answer could be handy:
increment state
|> isUnionCase <# StateTwo #>
|> should equal true
Note that it's a bit verbose because you need a function call before comparing values.
A similar but lighter approach could be comparison of tags:
// Copy from https://stackoverflow.com/a/3365084
let getTag (a:'a) =
let (uc,_) = Microsoft.FSharp.Reflection.FSharpValue.GetUnionFields(a, typeof<'a>)
uc.Name
increment state
|> getTag
|> should equal "StateTwo"
Beware that this is not type-safe and you can easily misspell a union case name.
What I would do is to create a similar DUs for comparison purpose:
type MyStateCase =
| StateOneCase
| StateTwoCase
let categorize = function
| StateOne _ -> StateOneCase
| StateTwo _ -> StateTwoCase
In this way, you define categorize once and use it multiple times.
increment state
|> categorize
|> should equal StateTwoCase
It appears FSUnit doesn't (or can't, I'm not sure) directly support this use case.
The next best thing I've found is to declare a TestResult type like the following and use a match to reduce the result to this type.
type TestResult =
| Pass
| Fail of obj
Here is the reducing match
let testResult =
match result with
| OptionA(_) -> Pass
| other -> Fail(other)
Now you can just use should equal to ensure the correct result.
testResult |> should equal Pass
The benefits of this solution are strong typing but more importantly in the failure case you can see what the invalid result was.
It doesn't look very elegant, but you can extract type from a value of state:
let instanceOfState (state: 'a) =
instanceOfType<'a>
And then use it in the test:
(increment state) |> should be (instanceOfState <| StateTwo 88)
EDIT
Yes, unfortunately the type is always MyState. Looks like pattern matching or ugly reflection are inevitable.
What if FsUnit already supports an assertion against a specific union case, albeit one restricted to values of the type Microsoft.FSharp.Core.Choice<_,...,_>?
Let's leverage this with a multi-case active pattern, which uses Reflection to check against the union case name.
open System.Reflection
open Microsoft.FSharp.Reflection
let (|Pass|Fail|) name (x : obj) =
let t = x.GetType()
if FSharpType.IsUnion t &&
t.InvokeMember("Is" + name,
BindingFlags.GetProperty, null, x, null )
|> unbox then Pass
else Fail x
Should be working now:
increment state
|> (|Pass|Fail|) "StateTwo"
|> should be (choice 1)
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"