let bindings and constructors in F# - f#

I am defining a stopwatch in F#:
open System.Diagnostics
let UptimeStopwatch = Stopwatch.StartNew()
and I am printing every 3 seconds with
printfn "%A" UptimeStopwatch.Elapsed
and every time i'm getting "00:00:00.0003195" or something similarly small. Is F# calling the constructor every time I reference UptimeStopwatch? If so, how do I get around this ad achieve the desired result? This is a confusing intermingling of functional and imperative programming.

F# seems to interpret statements like
let MyFunction = DoSomething()
and
let MyFunction() = DoSomething()
differently. The first binds the return value of DoSomething() to the variable MyFunction, and the second binds the action DoSomething() to the function MyFunction().
My usage of UptimeStopwatch was correct, and the error was elsewhere in my implementation.

I see you already found a problem elsewhere in your code, but the two lines in your question still take some time to run and, interestingly, you can make the overhead smaller.
When I run the two lines in your sample, it prints a value around 0.0002142. You can make that smaller by storing the elapsed time using let, because there is some overhead associated with constructing a representation of the printf format string (the first argument):
let UptimeStopwatch = Stopwatch.StartNew()
let elapsed = UptimeStopwatch.Elapsed
printfn "%A" elapsed
This prints on average a number around 0.0000878 (two times smaller). If you use Console, the result is similar (because the Elapsed property is obtained before Console is called and nothing else needs to be done in the meantime):
let UptimeStopwatch = Stopwatch.StartNew()
System.Console.WriteLine(UptimeStopwatch.Elapsed)

Related

Using f# to mimic linux touch command, need help implementing

I am trying to write a f# program which mimics the touch command in linux, it checks a file paths exists if it does time stamp is updated, if it doesnt exist file is created. How do i implement this correctly?
I've tried using .net functions which i think essentially do the functions i need. I am working with file.exists, file.create and file.setlastaccesstime
// Learn more about F# at http://fsharp.org
open System.IO
type Filepath = string
let touch =
let checkExists filePath =
if File.Exists filePath
then Result.Ok (filePath:Filepath)
else Result.Error "File does not exist"
let path = Console.ReadLine()
let update =
path = Console.ReadLine()
if File.Exists(path)
File.Create(path)
else File.SetLastAccessTime(path, DateTime.Now)
[<EntryPoint>]
let main argv =
printfn "Touch command for windows"
-> touch()
-> update()
0 // return an integer exit code```
Your code has several problems. I'll try to go through them one by one.
First, the indentation of the code in your question is totally messed up. If this is a direct copy and paste from your code, the first thing we need to do is fix the indentation: in F#, indentation is significant, and determines code blocks. (If your question's indentation is messed up because you fiddled with the indentation in the Stack Overflow question editor and your actual code indentation is fine, then consider this a refresher on how F# indentation works).
In F#, these two code blocks do something different:
if value = 5 then
printfn "Five"
printfn "Value: %d" value
This will always print "Value: 3" or "Value: 27" or whatever, and will also print the word "Five" if the value is exactly 5. But this next code block does something else:
if value = 5 then
printfn "Five"
printfn "Value: %d" value
This will either print nothing at all, or it will print the word "Five" followed on the next line by "Value: 5". That's because the second printfn function call is indented at the same level as the first one, meaning it's part of the if block.
Also, a let statement needs to be followed either by a value on the same line, or by an indented block:
let value = 5
let otherValue =
if value < 5 then
5
else
3
After this is executed, the value of otherValue will be 3. Also, the code block under let otherValue = will only be executed once. That's because otherValue is not a function, it's a value. If you wanted otherValue to be a function, you would need to give it parameters:
let calculateValue inputValue =
if inputValue < 5 then
5
else
3
And now you can call that function like:
let value = 5
let otherValue = calculateValue value
// Now otherValue is equal to 3
This brings us to the second problem your code has, which is that you clearly intend touch and update to be functions, but you didn't give them parameters. Which means that they're values which are only executed once. You need to turn let touch = into let touch () = to make touch a function instead of a value, and same for update.
Another problem you have is more of a design issue: your update function is doing two things. It's reading a value from the console, and it's taking actions based on that value. It's much better design to have each function do only one thing: let your update function take path as a parameter, and then elsewhere you can have the code that reads path from the console and calls update path. This makes it much easier to write unit tests that test the update function, because instead of having to somehow figure out how to hook up your unit tests to stdin, you can just have your tests call your update function.
Another issue that Guran pointed out in a comment (thanks!) is that your update function has the logic backwards. You wrote "if file exists, create file, else set last access time". It should be the other way around. I missed this in the first version of this answer, so I've updated my fixed code below to correct the order of the if...then...else block in update.
Another issue I see is: what is your touch function (currently it's a value, but you clearly intended it to be a function) supposed to be doing? The only thing inside your let touch = block is other function definitions; the touch code block never actually calls the functions it defines. Which means it's useless: by having those function definitions inside the touch code block, you're hiding them from any code outside the touch code block, yet the touch code block never calls them. Functions defined at the top level of a module are visible to any code that can access the module. Functions (and variables) defined inside a code block are visible only in the scope of that code block. This is useful for encapsulating things that shouldn't be visible to the outside world, e.g. in the following example:
let counter() =
let mutable value = 0
let update() =
value <- value + 1
value
update
Here, the value variable inside counter() is not accessible to the rest of the world. Also, notice how I've written update with no parentheses as the last line of the let counter() = code block: that means that the function named update will be the return value of counter(). In other words, when you call counter(), you get a function that, each time you call it, will return a new value that is the previous value plus 1. But two different counters are separate from each other:
let a = counter()
let b = counter()
let a1 = a()
let b1 = b()
let a2 = a()
let b2 = b()
printfn "A1: %d" a1
printfn "A2: %d" a2
printfn "B1: %d" b1
printfn "B2: %d" b2
This will print "A1: 1", "A2: 2", "B1: 1", and then "B2: 2". Now as an exercise, what would happen if I replaced let counter() = with let counter = in the above code? (I would also have to change let a = counter() to let a = counter, and same for let b = ...). Try to guess what would happen, then try it and see if you were right. (Hint: values, unlike functions, are only executed once).
And one final thing: the arrows in your main function are not correct. That's not what the -> operator is for. If you need to call several functions in a row, just write the function calls one after the other.
Okay, that's as much as I can do right now to help you fix your code's problems. There are more issues (it would be better to get your paths from argv rather than from Console.ReadLine(), for example) but those can wait until you have a bit more F# experience under your belt. Here's your code with just the fixes I've mentioned so far. Oh, and one more fix: I'm deleting the let touch = line since I can't tell what you intended to put in your touch function. So here's your code, somewhat fixed but still in need of more fixes:
open System.IO
type Filepath = string
// NOTE: This function is unused. Why do you have it?
let checkExists filePath =
if File.Exists filePath
then Result.Ok (filePath:Filepath)
else Result.Error "File does not exist"
let update path =
// Note: the "then" and "else" blocks are swapped from your original code
if File.Exists(path)
then File.SetLastAccessTime(path, DateTime.Now)
else File.Create(path)
[<EntryPoint>]
let main argv =
printfn "Touch command for windows"
let path = Console.ReadLine()
update path
0 // return an integer exit code

Entry point issue in F#

I have the following program :
let readStoriesInQAForm =
printfn "Inside the let!"
0
[<EntryPoint>]
let main argv =
printfn "Ah! entering point to the main!"
System.Console.ReadKey() |> ignore
0 // return an integer exit code
I was expecting to get the following output (since main is the entry point, and there is no function call):
Ah! entering point to the main!
But I get this, when I compiler and run it in VS 2013:
Inside the let!
Ah! entering point to the main!
What is my mistake?
As John Palmer describes in his answer, F# code is executed from top to bottom. The let keyword binds a value to a name - in this case, the value 0 is bound to the readStoriesInQAForm name.
Apart from primitive values, you can also bind functions to names; F# is a Functional programming language, so functions are values too. If you bind a function to a name, you can execute that function by invoking it.
However, readStoriesInQAForm isn't a function - it's a primitive value (0), and it gets bound before main is called, in order to make that value available for main. In this particular case, the way the let binding is defined, it has a side-effect of printing to Standard Out when the binding occurs. (In general, in Functional Programming, the more you can avoid side-effects, the better.)
If you want to avoid this behaviour, change the let binding from a a primitive value to a function:
let readStoriesInQAForm () =
printfn "Inside the let!"
0
Better yet would be to bind the name to the value without any side-effect:
let readStoriesInQAForm = 0
In a F# program, the code is essentially run from top to bottom, so that any values needed later are available.
For example, if you had written:
[<EntryPoint>]
let main argv =
printfn "Ah! entering point to the main!"
printfn readStoriesInQAForm
System.Console.ReadKey() |> ignore
0 // return an integer exit code
The observed behaviour makes perfect sense as it would be illogical to jump out of main to calculate a constant value.
To avoid this issue, you want to make readStoriesInQAForm a function, like so:
let readStoriesInQAForm() = ...
You're not declaring a function, you're declaring a value. It's missing ():
let readStoriesInQAForm() =

What is the effect of "if false then ()" in the Computer Language Benchmarks Game's F# Threadring entry?

The Computer Language Benchmarks Game's F# entry for Threadring contains a seemingly useless line: if false then (). When I comment out this line, the program runs much faster (~2s vs ~55s for an input of 50000000) and produces the same result. How does this work? Why is this line there? What exactly is the compiler doing with what appears to be a no-op?
The code:
let ringLength = 503
let cells = Array.zeroCreate ringLength
let threads = Array.zeroCreate ringLength
let answer = ref -1
let createWorker i =
let next = (i+1)%ringLength
async { let value = cells.[i]
if false then ()
match value with
| 0 -> answer := i+1
| _ ->
cells.[next] <- value - 1
return! threads.[next] }
[<EntryPoint>]
let main args =
cells.[0] <- if args.Length>0 then int args.[0] else 50000000
for i in 0..ringLength-1 do
threads.[i]<-createWorker i
let result = Async.StartImmediate(threads.[0])
printfn "%d" !answer
0
I wrote this code originally. I don't remember the exact reason I added the line, but I'm guessing that, without it, the optimizer would do something I thought was outside of the spirit of the benchmark game. The reason for using asyncs in the first place is to achieve tail-call continuation to the next async (which is what makes this perform so much better than C# mono).
- Jomo
If the computation expression contains if false then () then the asynchronous workflow gets translated a bit differently. With the line, it uses async.Combine. Slightly simplified code looks like:
async.Delay(fun () ->
value = cells.[i]
async.Combine
( async.Return(if false then ())
async.Delay(fun () ->
match value with (...) ) ))
The translation inserts Combine because the (potentially) asynchronous computation done by if loop needs to be combined with the following code. Now, if you delete if you get something like:
async.Delay(fun () ->
value = cells.[i]
match value with (...) ) ))
The difference is that now a lot more work is done immediately in the function passed to Delay.
EDIT: I thought this caused a difference because the code uses Async.StartImmediate instead of Async.Start, but that does not seem to be the case. In fact, I do not understand why the code uses asynchronous workflows at all...
EDIT II.: I'm not entirely sure about Mono, but it definitely does replicate in the F# interactive - there, the version with Combine is about 4 times slower (which is what I'd expect, because of the function allocation overhead).

Measure time of execution in F#

Please post code for displaying time in F#. I noticed that you can measure it from F# interactive with #time directive, but I don't know how to execute program from FSI
Thanks
I would just use the .NET Stopwatch class.
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
...
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
From msdn:
By itself, #time toggles whether to display performance information.
When it is enabled, F# Interactive measures real time, CPU time, and
garbage collection information for each section of code that is
interpreted and executed.
So to test you function you have to open F# interactive console and execute your function in it (one way to do it is to select your function, right click and chose Execute in Interactive)
Then make a call to your function in Interactive like that for example:
// define your function first either in interactive console or in your document:
let square x = x * x
// in interactive
#time
square 10
#time
You will see how much of real time and CPU time were spent on computation and a bit of information from garbage collector
Check out the timer function in the F Sharp Programming wikibook. It is defined like this:
let duration f =
let timer = new System.Diagnostics.Stopwatch()
timer.Start()
let returnValue = f()
printfn "Elapsed Time: %i" timer.ElapsedMilliseconds
returnValue
Whilst being used like this:
let sample() = System.Threading.Thread.Sleep(2)
duration ( fun() -> sample() )
// or
duration sample
You could also create custom computation expression to hide actual measuring logic, e.g.:
timer {
// your code goes here
}
See more examples here: https://fsharpforfunandprofit.com/posts/computation-expressions-bind/

F# Functions vs. Values

This is a pretty simple question, and I just wanted to check that what I'm doing and how I'm interpreting the F# makes sense. If I have the statement
let printRandom =
x = MyApplication.getRandom()
printfn "%d" x
x
Instead of creating printRandom as a function, F# runs it once and then assigns it a value. So, now, when I call printRandom, instead of getting a new random value and printing it, I simply get whatever was returned the first time. I can get around this my defining it as such:
let printRandom() =
x = MyApplication.getRandom()
printfn "%d" x
x
Is this the proper way to draw this distinction between parameter-less functions and values? This seems less than ideal to me. Does it have consequences in currying, composition, etc?
The right way to look at this is that F# has no such thing as parameter-less functions. All functions have to take a parameter, but sometimes you don't care what it is, so you use () (the singleton value of type unit). You could also make a function like this:
let printRandom unused =
x = MyApplication.getRandom()
printfn "%d" x
x
or this:
let printRandom _ =
x = MyApplication.getRandom()
printfn "%d" x
x
But () is the default way to express that you don't use the parameter. It expresses that fact to the caller, because the type is unit -> int not 'a -> int; as well as to the reader, because the call site is printRandom () not printRandom "unused".
Currying and composition do in fact rely on the fact that all functions take one parameter and return one value.
The most common way to write calls with unit, by the way, is with a space, especially in the non .NET relatives of F# like Caml, SML and Haskell. That's because () is a singleton value, not a syntactic thing like it is in C#.
Your analysis is correct.
The first instance defines a value and not a function. I admit this caught me a few times when I started with F# as well. Coming from C# it seems very natural that an assignment expression which contains multiple statements must be a lambda and hence delay evaluated.
This is just not the case in F#. Statements can be almost arbitrarily nested (and it rocks for having locally scoped functions and values). Once you get comfortable with this you start to see it as an advantage as you can create functions and continuations which are inaccessible to the rest of the function.
The second approach is the standard way for creating a function which logically takes no arguments. I don't know the precise terminology the F# team would use for this declaration though (perhaps a function taking a single argument of type unit). So I can't really comment on how it would affect currying.
Is this the proper way to draw this
distinction between parameter-less
functions and values? This seems less
than ideal to me. Does it have
consequences in currying, composition,
etc?
Yes, what you describe is correct.
For what its worth, it has a very interesting consequence able to partially evaluate functions on declaration. Compare these two functions:
// val contains : string -> bool
let contains =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
fun person -> people.Contains(person)
// val contains2 : string -> bool
let contains2 person =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
people.Contains(person)
Both functions produce identical results, contains creates its people set on declaration and reuses it, whereas contains2 creates its people set everytime you call the function. End result: contains is slightly faster. So knowing the distinction here can help you write faster code.
Assignment bodies looking like function bodies have cought a few programmers unaware. You can make things even more interesting by having the assignment return a function:
let foo =
printfn "This runs at startup"
(fun () -> printfn "This runs every time you call foo ()")
I just wrote a blog post about it at http://blog.wezeku.com/2010/08/23/values-functions-and-a-bit-of-both/.

Resources