F# - This code isn't compiling for me - f#

This code isn't compiling for me: let countDown = [5L .. −1L .. 0L];;
I have a book (page 33) that says it should return this:
val countDown : int list = [5L; 4L; 3L; 2L; 1L; 0L]
Compiler Error:
Program.fs(42,24): error FS0010: Unexpected character '−' in expression
>
> let countDown = [5L .. −1L .. 0L];;
let countDown = [5L .. −1L .. 0L];;
-----------------------^
The book's wrong. but why? is it an update to the language? what is the way to achieve that?
Edit: the problem was that the − character copied from the PDF, isn't the - character.

Your original code works fine for me even without the modifications that Igor suggested:
Microsoft (R) F# 2.0 Interactive build 4.0.30319.1
Copyright (c) Microsoft Corporation. All Rights Reserved.
> let l = [ 10L .. -1L .. 0L ];;
val l : int64 list = [10L; 9L; 8L; 7L; 6L; 5L; 4L; 3L; 2L; 1L; 0L]
A possible subtle error is that if you (for example) pasted the code from Word (or some other program), it may have replaced the - symbol with some other type of dash that looks the same, but has actually a different code.
Another way to break the code is to remove some spaces - for example, there must be a space between .. and -1L. Otherwise, I don't see any reason why it shouldn't work.

Try this:
let countDown = [5L .. (-1L) .. 0L];;
Or this:
let countDown = [5 .. -1 .. 0];;
Both of the above will work.
Here is some output:
> let countDown = [5 .. -1 .. 0];;
val countDown : int list = [5; 4; 3; 2; 1; 0]
> let countDown = [5L .. (-1L) .. 0L];;
val countDown : int64 list = [5L; 4L; 3L; 2L; 1L; 0L]

Related

Why does "array[index]" return "nil"?

this problem seems very simple but I cannot find a solution for it, actually I don't even know what is wrong!!!
So basically I have this Lua code:
io.write("\nPlease provide the message to be decyphered: ")
message = io.read()
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
fib = 0
while c < (seq - 10) do
fib = fib + 1
ffib[fib] = c
a = b
b = c
c = a + b
end
decyphered = ""
for i = 1,seq do
decyphered = table.concat{decyphered, message:sub(ffib[i],ffib[i])}
end
io.write("\nDecyphered message: ", decyphered, "\n\n")
and trying to access ffib[fib] returns nil. So trying to message:sub(ffib[i]... later throws an error.
When I try accessing ffib's values manually, ffib[1] for example, it works alright, it's only when trying to access it with an iterator that it screws up.
Somewhere else in my code I have this:
io.write("\nPlease provide the message to be cyphered: ")
message = io.read()
cyphered = ""
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
for fib = 1,seq do
ffib[fib] = c
a = b
b = c
c = a + b
end
which is basically the same thing but instead of using a while loop, it uses a for loop, and it works just fine!
Please help me solve this I am going insane.
Alright, I figured it out!
io.write("\nPlease provide the message to be decyphered: ")
message = io.read()
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
fib = 0
while c < (seq - 10) do
fib = fib + 1
ffib[fib] = c
a = b
b = c
c = a + b
end
decyphered = ""
for i = 1,seq do <--------------
decyphered = table.concat{decyphered, message:sub(ffib[i],ffib[i])}
end
io.write("\nDecyphered message: ", decyphered, "\n\n")
I was using the wrong variable in the for loop, so it was looping through the entire message length instead of the fibonacci array length, the "nil" values were indexes out of bounds!
To correct this, I simply changed seq for #ffib in that For Loop, marked by an arrow.
Thanks everyone who tried to help me anyway!
this part doesn't make much sense I think
while c < (seq - 10) do
Why the minus 10? ffib will have less entries than seq while in the loop after that you expect a value in ffib from 1 to seq
And even if you change it to
while c < seq do
Then there still won't be enough for messages larger than length 2.
If anything, you might want to do
while c < (seq + 10) do
But even there you will run into an issue when the message is a certain length.
I'm also not familiar with that algorithm, but it looks pretty weird to me and I wonder what it actually establishes

How to look for anagrams in 1 or 2 dictionaries?

This is our code now:
#anagram is a word formed by rearranging the letters of a different word
text = open("words.txt")
counter = 0
d = {}
e = {}
for word in text:
w = word
a = list(word)
s = sorted(a)
counter += 1
d[counter] = s
e[counter] = s
print(d)
print(e)
We want to ask python to show us the words which have the same values/letters. So for example: AAB is the same as BAA.
Our file exists from:
aba
aab
acaba
ackba
abaca
casaba
Does anyone know how to program this?

Incrementation in Lua

I am playing a little bit with Lua.
I came across the following code snippet that have an unexpected behavior:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
Lua runs the program without any error but does not print 2 6 15 as expected. Why ?
-- starts a single line comment, like # or // in other languages.
So it's equivalent to:
a = 3;
b = 5;
c = a
LUA doesn't increment and decrement with ++ and --. -- will instead start a comment.
There isn't and -- and ++ in lua.
so you have to use a = a + 1 or a = a -1 or something like that
If you want 2 6 15 as the output, try this code:
a = 3
b = 5
c = a * b
a = a - 1
b = b + 1
print(a, b, c)
This will give
3 5 3
because the 3rd line will be evaluated as c = a.
Why? Because in Lua, comments starts with --. Therefore, c = a-- * b++; // some computation is evaluated as two parts:
expression: c = a
comment: * b++; //// some computation
There are 2 problems in your Lua code:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
One, Lua does not currently support incrementation. A way to do this is:
c = a - 1 * b + 1
print(a, b, c)
Two, -- in Lua is a comment, so using a-- just translates to a, and the comment is * b++; // some computation.
Three, // does not work in Lua, use -- for comments.
Also it's optional to use ; at the end of every line.
You can do the following:
local default = 0
local max = 100
while default < max do
default = default + 1
print(default)
end
EDIT: Using SharpLua in C# incrementing/decrementing in lua can be done in shorthand like so:
a+=1 --increment by some value
a-=1 --decrement by some value
In addition, multiplication/division can be done like so:
a*=2 --multiply by some value
a/=2 --divide by some value
The same method can be used if adding, subtracting, multiplying or dividing one variable by another, like so:
a+=b
a-=b
a/=b
a*=b
This is much simpler and tidier and I think a lot less complicated, but not everybody will share my view.
Hope this helps!

Huge performance difference running f# same code on fsi 4.0.30319.1 and 2.0.0.0

I am running the same F# code with the two versions of fsi.exe which I can find under my FSharp-2.0.0.0 install:
C:\Program Files\FSharp-2.0.0.0\bin\fsi.exe - Microsoft (R) F# 2.0 Interactive build 2.0.0
C:\Program Files\FSharp-2.0.0.0\v4.0\bin\fsi.exe - Microsoft (R) F# 2.0 Interactive build 4.0.30319.1
What I find is that the same code runs about three times faster on the 2.0.0.0 build. Does this make any sense? Is there something messed up with my environment or possibly code??
Incidentally, the reason I am trying to use the v4.0 build is to be able to use the TPL and compare sequential and parallel implementations of my code. When my parallel implementation was much slower than the sequential one, after much head-scratching I realized that the parallel version was running under a different fsi.exe, and that's when I realized that the same (sequential) version of the code is much slower under version 4.0.
Thanks in advance for any help
IS
The code:
module Options
//Gaussian module is from http://fssnip.net/3g, by Tony Lee
open Gaussian
//The European Option type
type EuropeanOption =
{StockCode: string
StockPrice: float
ExercisePrice: float
NoRiskReturn: float
Volatility: float
Time: float
}
//Read one row from the file and return a European Option
//File format is:
//StockCode<TAB>StockPrice,ExercisePrice,NoRiskReturn,Volatility,Time
let convertDataRow(line:string) =
let option = List.ofSeq(line.Split('\t'))
match option with
| code::data::_ ->
let dataValues = (data.Split(','))
let euopt = {StockCode = code;
StockPrice = float (dataValues.[0]);
ExercisePrice = float (dataValues.[1]);
NoRiskReturn = float (dataValues.[2]);
Volatility = float (dataValues.[3]);
Time = float (dataValues.[4])
}
euopt
| _ -> failwith "Incorrect Data Format"
//Returns the future value of an option.
//0 if excercise price is greater than the sum of the stock price and the calculated asset price at expiration.
let futureValue sp ep nrr vol t =
//TODO: Is there no better way to get the value from a one-element sequence?
let assetPriceAtExpiration = sp+sp*nrr*t+sp*sqrt(t)*vol*(Gaussian.whiteNoise |> Seq.take 1 |> List.ofSeq |> List.max)
[0.0;assetPriceAtExpiration - ep] |> List.max
//Sequence to hold the values generated by the MonteCarlo iterations
//50,000 iterations is the minimum for a good aprox to the Black-Scholes equation
let priceValues count sp ep nrr vol t =
seq { for i in 1..count
-> futureValue sp ep nrr vol t
}
//Discount a future to a present value given the risk free rate and the time in years
let discount value noriskreturn time =
value * exp(-1.0*noriskreturn*time)
//Get the price for a European Option and a given number of Monte Carlo iterations (use numIters >= 50000)
let priceOption europeanOption numIters =
let futureValuesSeq = priceValues numIters europeanOption.StockPrice europeanOption.ExercisePrice europeanOption.NoRiskReturn europeanOption.Volatility europeanOption.Time
//The simulated future value is just the average of all the MonteCarlo runs
let presentValue = discount (futureValuesSeq |> List.ofSeq |> List.average) europeanOption.NoRiskReturn europeanOption.Time
//Return a list of tuples with the stock code and the calculated present value
europeanOption.StockCode + "_to_" + string europeanOption.Time + "_years \t" + string presentValue
module Program =
open Options
open System
open System.Diagnostics
open System.IO
//Write to a file
let writeFile path contentsArray =
File.WriteAllLines(path, contentsArray |> Array.ofList)
//TODO: This whole "method" is sooooo procedural.... is there a more functional way?
//Unique code for each run
//TODO: Something shorter, please
let runcode = string DateTime.Now.Month + "_" + string DateTime.Now.Day + "_" + string DateTime.Now.Hour + "_" + string DateTime.Now.Minute + "_" + string DateTime.Now.Second
let outputFile = #"C:\TMP\optionpricer_results_" + runcode + ".txt"
let statsfile = #"C:\TMP\optionpricer_stats_" + runcode + ".txt"
printf "Starting"
let mutable stats = ["Starting at: [" + string DateTime.Now + "]" ]
let stopWatch = Stopwatch.StartNew()
//Read the file
let lines = List.ofSeq(File.ReadAllLines(#"C:\tmp\9000.txt"))
ignore(stats <- "Read input file done at: [" + string stopWatch.Elapsed.TotalMilliseconds + "]"::stats)
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
//Build the list of European Options
let options = lines |> List.map convertDataRow
ignore(stats <- ("Created Options done at: [" + string stopWatch.Elapsed.TotalMilliseconds + "]")::stats)
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
//Calculate the option prices
let results = List.map (fun o -> priceOption o 50000) options
ignore(stats <- "Option prices calculated at: [" + string stopWatch.Elapsed.TotalMilliseconds + "]"::stats)
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
//Write results and statistics
writeFile outputFile results
ignore(stats <- "Output file written at: [" + string stopWatch.Elapsed.TotalMilliseconds + "]"::stats)
ignore(stats <- "Total Ellapsed Time (minus stats file write): [" + string (stopWatch.Elapsed.TotalMilliseconds / 60000.0) + "] minutes"::stats)
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
writeFile statsfile (stats |> List.rev)
stopWatch.Stop()
ignore(Console.ReadLine())
I haven't run your code but it looks like you're creating lots of linked lists. That is very inefficient but the representation of lists was changed in recent years and the new representation is slower.

List comprehensions with float iterator in F#

Consider the following code:
let dl = 9.5 / 11.
let min = 21.5 + dl
let max = 40.5 - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
"a" should have 21 elements but has got only 20 elements. The "max - dl" value is missing. I understand that float numbers are not precise, but I hoped that F# could work with that. If not then why F# supports List comprehensions with float iterator? To me, it is a source of bugs.
Online trial: http://tryfs.net/snippets/snippet-3H
Converting to decimals and looking at the numbers, it seems the 21st item would 'overshoot' max:
let dl = 9.5m / 11.m
let min = 21.5m + dl
let max = 40.5m - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
let lastelement = List.nth a 19
let onemore = lastelement + dl
let overshoot = onemore - max
That is probably due to lack of precision in let dl = 9.5m / 11.m?
To get rid of this compounding error, you'll have to use another number system, i.e. Rational. F# Powerpack comes with a BigRational class that can be used like so:
let dl = 95N / 110N
let min = 215N / 10N + dl
let max = 405N / 10N - dl
let a = [ for z in min .. dl .. max -> z ] // Has 21 elements
let b = a.Length
Properly handling float precision issues can be tricky. You should not rely on float equality (that's what list comprehension implicitely does for the last element). List comprehensions on float are useful when you generate an infinite stream. In other cases, you should pay attention to the last comparison.
If you want a fixed number of elements, and include both lower and upper endpoints, I suggest you write this kind of function:
let range from to_ count =
assert (count > 1)
let count = count - 1
[ for i = 0 to count do yield from + float i * (to_ - from) / float count]
range 21.5 40.5 21
When I know the last element should be included, I sometimes do:
let a = [ for z in min .. dl .. max + dl*0.5 -> z ]
I suspect the problem is with the precision of floating point values. F# adds dl to the current value each time and checks if current <= max. Because of precision problems, it might jump over max and then check if max+ε <= max (which will yield false). And so the result will have only 20 items, and not 21.
After running your code, if you do:
> compare a.[19] max;;
val it : int = -1
It means max is greater than a.[19]
If we do calculations the same way the range operator does but grouping in two different ways and then compare them:
> compare (21.5+dl+dl+dl+dl+dl+dl+dl+dl) ((21.5+dl)+(dl+dl+dl+dl+dl+dl+dl));;
val it : int = 0
> compare (21.5+dl+dl+dl+dl+dl+dl+dl+dl+dl) ((21.5+dl)+(dl+dl+dl+dl+dl+dl+dl+dl));;
val it : int = -1
In this sample you can see how adding 7 times the same value in different order results in exactly the same value but if we try it 8 times the result changes depending on the grouping.
You're doing it 20 times.
So if you use the range operator with floats you should be aware of the precision problem.
But the same applies to any other calculation with floats.

Resources