another noob question regarding F#.
If I have the following code...
let ExeC =
printfn "c"
3
let ExeB b =
printfn "b"
2
let ExeA =
printfn "a"
1
printfn "Example %d " ExeA
printfn "Example %d " (ExeB 1)
printfn "Example %d " ExeC
The output is as follows...
c
a
Example 1
b
Example 2
Example 3
What seems unusual here is the order that the code is executing in. In a previous question Brian mentioned something about expressions, I was hoping someone could explain this a bit more. It almost seems like the compiler is intelligently pre-executing things to calculate values... but I don't know?
ExeA and ExeC aren't functions, but single values. The compiler ensures that values initialise in the order in which they're declared in the source file, so what's happening here is:
ExeC initialises
ExeA initialises
Example 1 is printed, using ExeA's initialised value
The ExeB function is called as normal
Example 3 is printed, using ExeC's initialised value
If you want ExeA and ExeC to be truly lazy -- that is, to control when their side effects run -- you could turn them into functions that accept unit:
let ExeC () =
printfn "c"
3
let ExeB b =
printfn "b"
2
let ExeA () =
printfn "a"
1
printfn "Example %d " (ExeA ())
printfn "Example %d " (ExeB 1)
printfn "Example %d " (ExeC ())
As a follow up to Tim's answer, I thought you might appreciate some further insight into what you've stumbled upon. In your example, ExeC and ExeA take advantage of the functional style of organizing code through lexical scoping and closures. Let me demonstrate a more powerful example.
let calc n =
//...
let timesPieDiv4 =
let pie = 3.14
let pieDiv4 = pie/4.
n * pieDiv4
//...
Here again timesPieDiv4 is not a function, but does have a body which contains a series of sub calculations which are not exposed to the rest of the calc function. In a language like C#, you have two options neither of which appeals to me. The first option is to simply declare pie and pieDiv4 within the main body of calc, but then it's less clear how they are being used and you dirty your variable space. The other option is to factor those sub calculations out into a separate private helper function. But I dislike such functions, because with many it becomes hard to analyze your complex algorithms since you are constantly darting around looking up various implementation pieces. Plus it's a lot of boiler plate code and value passing. That's why F# functions are "public" by default, lexical scoping and closures allow you to hierarchically organize "private" functions and values within your public facing functions.
Related
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
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).
Extremely just-started-yesterday new to F#.
What I want: To write code that parses the string "2 + 2" into (using as an example code from the tutorial project) Expr.Add(Expr.Num 2, Expr.Num 2) for evaluation. Some help to at least point me in the right direction or tell me it's too complex for my first F# project. (This is how I learn things: By bashing my head against stuff that's hard)
What I have: My best guess at code to extract the numbers. Probably horribly off base. Also, a lack of clue.
let script = "2 + 2";
let rec scriptParse xs =
match xs with
| [] -> (double)0
| y::ys -> (double)y
let split = (script.Split([|' '|]))
let f x = (split[x]) // "This code is not a function and cannot be applied."
let list = [ for x in 0..script.Length -> f x ]
let result = scriptParse
Thanks.
The immediate issue that you're running into is that split is an array of strings. To access an element of this array, the syntax is split.[x], not split[x] (which would apply split to the singleton list [x], assuming it were a function).
Here are a few other issues:
Your definition of list is probably wrong: x ranges up to the length of script, not the length of the array split. If you want to convert an array or other sequence to a list you can just use List.ofSeq or Seq.toList instead of an explicit list comprehension [...].
Your "casts" to double are a bit odd - that's not the right syntax for performing conversions in F#, although it will work in this case. double is a function, so the parentheses are unnecessary and what you are doing is really calling double 0 and double y. You should just use 0.0 for the first case, and in the second case, it's unclear what you are converting from.
In general, it would probably be better to do a bit more design up front to decide what your overall strategy will be, since it's not clear to me that you'll be able to piece together a working parser based on your current approach. There are several well known techniques for writing a parser - are you trying to use a particular approach?
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/.
Could you, please, give a code snippet showing how to use Lua embedded in OCaml?
A simple example could be a "Hello, World" variant. Have OCaml prompt the user for a name. Then pass that name to a Lua function. Have Lua print a greeting and return the length of the name. Then have OCaml print a message about the length of the name.
Example:
user#desktop:~$ ./hello.opt
Name? User
Hello, User.
Your name is 4 letters long.
user#desktop:~$
[Edit]
As a non-C programmer, could I implement this without having to write an intermediary C program to pass the data between Lua and OCaml?
Following is a theoretical idea of what I would like to try. Unfortunately, line 3 of ocaml_hello.ml would need to know how to call the function defined in lua_hello.lua in order for the code to be valid.
lua_hello.lua
Defines lua_hello, which prints an argument and returns its length.
1 function lua_hello (name)
2 print ("Hello, "..name..".")
3 return (string.len (name))
4 end
ocaml_hello.ml
OCaml prompts for a name, calls the Lua function, and prints the return value.
1 let () = print_string "Name? "; flush stdout in
2 let name = input_line stdin in
3 let len = Lua_hello.lua_hello name in
4 Printf.printf "Your name is %d letters long." len; flush stdout;;
I'm not aware of a mature set of bindings for embedding the C implementation of Lua into OCaml. An immature set of bindings was posted on the Caml mailing list in 2004.
If you want to use the ML implementation you can find some examples in a paper called ML Module Mania. The ML implementation, unlike the C implementation, guarantees type safety, but to do so it uses some very scurvy tricks in the ML module system. If you are asking basic questions, you probably want to avoid this.
In your example it's a little hard to guess where you want the function to come from. I suggest you either ask for a C example or give people a C example and ask how it could be realized in OCaml (though I think bindings are going to be a problem).
Edit
In response to the revised question, it's pretty complicated. The usual model is that you would put Lua in charge, and you would call Objective Caml code from Lua. You're putting Caml in charge, which makes things more complicated. Here's a rough sketch of what things might look like:
let lua = Lua.new() (* create Lua interpreter *)
let chunk = LuaL.loadfile lua "hello.lua" (* load and compile the file hello.lua *)
let _ = Lua.call lua 0 0 (* run the code to create the hello function *)
let lua_len s =
(* push the function; push the arg; call; grab the result; pop it; return *)
let _ = Lua.getglobal lua "lua_hello" in
let _ = Lua.pushstring lua s in
let _ = Lua.call lua 1 1 in
let len = Lua.tointeger lua (-1) in
let _ = Lua.pop lua 1 in
len
let () = print_string "Name? "; flush stdout
let name = input_line stdin
let len = lua_len name
Printf.printf "Your name is %d letters long." len; flush stdout;;
Again, I don't know where you'll get the bindings for the Lua and LuaL modules.
On further reflection, I'm not sure if you can do this with the official C implementation of Lua, because I think OCaml believes it owns main(). You'd have to find out if OCaml could be packaged as a library from a C main program.
For an example of putting Lua-ML in charge, you can get Lua-ML standalone from Cminusminus.org, and you can also check out the examples in the paper on Lua-ML as well as the source code to the QC-- compiler itself.