Compiler warning: FS0058: Possible incorrect indentation - f#

I wrote this code with Visual Studio but when I compile it, it gives me back these warnings:
FS0058: Possible incorrect indentation, this token is offside of context started at position 9:80. Try indenting this token further or using standard formatting .
But if I try to compile it with an OCaml compiler it works.
let converti_tempo = (fun x -> if x < 0 then failwith "error" else if x < 1000 then (0, 0, x) else
let rec m = x % 1000
let s = (x / 1000) % 60
let mm = ((x / 1000) / 60) % 60
in (mm,s ,m ));;

At the end of the first line you have an else. This implies that the expression of the else is going to be defined on the next line and thus will have to be indented all the way to the else and then a bit more. Code below:
let converti_tempo = (fun x -> if x < 0 then failwith "error" else if x < 1000 then (0, 0, x) else
let rec m = x % 1000
let s = (x / 1000) % 60
let mm = ((x / 1000) / 60) % 60
in (mm,s ,m ));;
You could also write it like this:
let converti_tempo = (fun x -> if x < 0 then failwith "error"
else if x < 1000 then (0, 0, x)
else
let rec m = x % 1000
let s = (x / 1000) % 60
let mm = ((x / 1000) / 60) % 60
in (mm,s ,m ));;

I would say this is a more "idiomatic" way of writing this function
let converti_tempo x =
if x < 0 then
failwith "error"
elif x < 1000 then
(0, 0, x)
else
let m = x % 1000
let s = x / 1000 % 60
let mm = x / 1000 / 60 % 60
(mm, s, m)

For me this compiler warning was caused by one of my "let"s not being properly aligned. Make sure all of your function declarations start at the very start of each new line.

Related

Represent finite coordinates as an F# type

I'm learning F# by implementing a board game engine. In accordance with the principle that invalid states should not be representable, I want to create a type which represents (x, y) coordinates (with x and y integers) where x and y must satisfy 0 <= x <= n and 0 <= y <= m. Creating an instance that does not satisfy those inequalities shouldn't compile. Is this possible?
I don't think compile time assurances on values like this are possible.
I would handle this with a private constructor and the Result or Option type depending whether I wanted to propagate error information.
type Position =
private {
X: int
Y: int
}
static member TryNew(x, y) =
if x >= 0 && x <= 10 then
if y >= 0 && y <=10 then
Ok {
X = x
Y = y
}
else
Error $"Supplied y ({y}) must be between 0 and 10"
else
Error $"Supplied x ({x}) must be between 0 and 10"
module Position =
let moveX1 pos =
Position.TryNew(pos.X + 1, pos.Y)
This does create the issue where Results are now everywhere in your code but they don't have to be visible or cause you a lot of typing. This problem is precisely what computation expression libraries e.g. FsToolkit.ErrorHandling are designed to eliminate.
let example =
result {
let! start = Position.TryNew(0,0)
let! next = start |> moveX1
}
There's no way to do this that takes integers as input, but it can be done with a type that only provides integers as output:
type XCoord = X0 | X1 | X2 with
member this.Int =
match this with
| X0 -> 0
| X1 -> 1
| X2 -> 2
static member (-)(xa : XCoord, xb: XCoord) =
xa.Int - xb.Int
type YCoord = Y0 | Y1 | Y2 with
member this.Int =
match this with
| Y0 -> 0
| Y1 -> 1
| Y2 -> 2
static member (-)(ya : YCoord, yb: YCoord) =
ya.Int - yb.Int
type Point = MkPoint of (XCoord * YCoord) with
member this.Ints =
let (MkPoint (x, y)) = this
x.Int, y.Int
static member (-)((MkPoint (ax, ay)), (MkPoint (bx, by))) =
ax - bx, ay - by
let ptA = MkPoint (X0, Y1)
let ptB = MkPoint (X2, Y0)
printfn "%A" ptA.Ints
printfn "%A" ptB.Ints
printfn "%A" (ptA - ptB)
I think this would be pretty clunky to use in practice, but it might work, depending on exactly what you want to do with it. I guess it's a case of "careful what you ask for". 😀

F# functional style approach much slower

Trying to learn F#, by solving some programming puzzles. I don't want to add too many details about the problem as I don't want to spoil the fun for others.
Basically, the issue is to find all 4-uples { (i,j,k,l) | i ^ j ^ k ^ l != 0 } with no repetition (eg., (1,1,1,2) and (1,1,2,1) are the same and should be counted just once).
I have found a O(n^3) approach which works, please see countImperative(a,b,c,d) below. But I also tried to refactor the code as to get rid of the nested for loops. However, I could not do so without a significant performance penalty. It was my impression that F#'s syntactic sugar would allow a more concise style (using pipes and folds), letting the compiler do the heavy-lifting to produce comparably fast code (compared to my nested for loops). The big performance hit comes from the calculation of the partial2 sum.
Here's the code:
open System
open System.Diagnostics
open System.Collections
module quadruples =
[<EntryPoint>]
let main argv =
let input = "2000 2000 2000 2000"
let ordered = [ for x in input.Split([|' '|]) -> Convert.ToInt32(x) ] |> List.sort
let a,b,c,d = ordered.[0], ordered.[1], ordered.[2], ordered.[3]
let inner(a,b) = a * (a-1) / 2 + a * (b-a)
let sw = new Stopwatch()
sw.Start()
let partial1 = [ 1.. b ] |> List.fold (fun acc j -> acc + (int64 ((min a j) * inner(c-j+1, d-j+1)))) 0L
sw.Stop()
let elapsed1 = (sw.ElapsedMilliseconds |> double) / 1000.0
printfn "Partial1: %f s" elapsed1
sw.Restart()
let combinations = [ for i in 1..a do for j in i+1..b do yield (j,i^^^j) ]
let range = [ 1..c ]
let partial2 = combinations |> List.fold(fun acc (j,x) -> acc + (range |> List.skip(j-1) |> List.fold(fun acc k -> if k ^^^ x < k || k ^^^ x > d then acc + 1L else acc) 0L)) 0L
sw.Stop()
let elapsed2 = (sw.ElapsedMilliseconds |> double) / 1000.0
printfn "Partial2: %f s" elapsed2
printfn "Functional: %d, Elapsed: %f s" (partial1 + partial2) (elapsed1 + elapsed2)
// "imperative" approach
let countImperative(a,b,c,d) =
let mutable count = seq { 1..b } |> Seq.fold (fun acc j -> acc + (int64 ((min a j) * inner(c-j+1, d-j+1)))) 0L
for i in 1..a do
for j in i+1..b do
let x = i ^^^ j
for k in j..c do
let y = x ^^^ k
if y < k || y > d then
count <- count + 1L
count
sw.Restart();
let count = countImperative(a,b,c,d)
sw.Stop()
printfn "Imperative: %d, Elapsed: %f s" count ((sw.ElapsedMilliseconds |> double) / 1000.0)
0 // return an integer exit code
So my question was, if there is any way to speed up the code (specifically the calculation of partial2) while maintaining F#'s nice syntax.

F#: why using outer function version faster than pass function as argument

Version (calc1) using direct outer function take about 1s.
But version (calc2) with pass function as parameter of function take about 2s, that is 2x slower. Why?
open System.Diagnostics
open System.Numerics
let width = 1920
let height = 1200
let xMin = -2.0
let xMax = 1.0
let yMin = -1.0
let yMax = 1.0
let scaleX x = float x * (xMax - xMin) / float width + xMin
let scaleY y = float y * (yMax - yMin) / float height - yMax
let fn (z:Complex) (c:Complex) = z * z + c
let calc1 width height =
let iterFn z c =
let rec iterFn' (z:Complex) c n =
if z.Magnitude > 2.0 || n >= 255 then n
else iterFn' (fn z c) c (n + 1)
iterFn' z c 0
Array.Parallel.init (width * height) (fun i ->
let x, y = i % width, i / width
let z, c = Complex.Zero, Complex(scaleX x, scaleY y)
(x, y, iterFn z c)
)
let calc2 width height fn =
let iterFn z c =
let rec iterFn' (z:Complex) c n =
if z.Magnitude > 2.0 || n >= 255 then n
else iterFn' (fn z c) c (n + 1)
iterFn' z c 0
Array.Parallel.init (width * height) (fun i ->
let x, y = i % width, i / width
let z, c = Complex.Zero, Complex(scaleX x, scaleY y)
(x, y, iterFn z c)
)
Execute in F# interactive get the following results:
> calc1 width height |> ignore
Real: 00:00:00.943, CPU: 00:00:03.046, GC gen0: 10, gen1: 8, gen2: 2
val it : unit = ()
> calc2 width height fn |> ignore
Real: 00:00:02.033, CPU: 00:00:07.484, GC gen0: 9, gen1: 8, gen2: 1
val it : unit = ()
F# 4.0.1, .NET 4.6.1
I suspect that in the first case, the fn is inlined.
Passing it as a paramter prevents this optimisation from occuring, so it is slower

f# calc variance function

I am working through an F# function that calculates variance. I'm trying to step through each iteration to get the correct answer but think im getitng off track somewhere because I keep getting the wrong answer. Could someone please walk me through one iteration of this function to get me back on track
let variance values
let average = Seq.average values
let length = Seq.length values
values
|> Seq.map (fun x -> 1.0 / float length * (x - average) ** 2.0)
|> Seq.sum
call is variance [1.0..6.0]
To me the first value passed is 1.0 so it would be (1.0 / 6 * (1.0-3.5) ** 2.0) and therefore .166 * -2.5 ** 2.0
I'm also unsure what the ** means in formula I'm assuming multiply.
Correct answer should be 2.9166666667
To make it easier to understand, you can rewrite the code as follows:
let variance values =
let average = Seq.average values
let length = Seq.length values
let sum = values
|> Seq.map (fun x -> (x - average) ** 2.0)
|> Seq.sum in sum / float length
variance [1.0..6.0] |> printfn "%A"
Print: 2.916666667
Link: https://dotnetfiddle.net/09PHXn
By iteration:
let variancetest values =
let average = Seq.average values
let length = Seq.length values
values
|> Seq.iteri(fun i x ->
printfn "%i [%f]: %f ^ 2 = %A" i x (x - average) ((x - average) ** 2.0))
let sum = values
|> Seq.map (fun x -> (x - average) ** 2.0)
|> Seq.sum
let flength = float length
printfn "Sum = %f" sum
printfn "1/length = %f" (1.0 / flength)
printfn "Result / length = %f" (sum / flength)
variancetest [1.0..6.0]
Print:
0 [1.000000]: -2.500000 ^ 2 = 6.25
1 [2.000000]: -1.500000 ^ 2 = 2.25
2 [3.000000]: -0.500000 ^ 2 = 0.25
3 [4.000000]: 0.500000 ^ 2 = 0.25
4 [5.000000]: 1.500000 ^ 2 = 2.25
5 [6.000000]: 2.500000 ^ 2 = 6.25
Sum = 17.500000
1/length = 0.166667
Result / length = 2.916667
https://dotnetfiddle.net/02r3qG

Using FSCheck generators

I have a function to generate doubles in a range:
let gen_doublein =
fun mx mn -> Arb.generate<float> |> Gen.suchThat ( (>) mx ) |> Gen.suchThat ( (<) mn )
and then a function to generate an array of 2 of these:
let gen_params:Gen<double array> =
gen { let! x = gen_doublein 0.0 20000.0
let! y = gen_doublein 0.0 2000.0
return [| x;y|] }
I put:
static member arb_params = Arb.fromGen gen_params
in the Generator class and register it. All seems OK. To test that this is all OK I have:
let f2 (xs:double array) :double= exp (-2.0*xs.[0]) + xs.[1]*exp (-2.0*xs.[0])
let fcheck fn xs = fn xs > 0.0
then using an array generator 'arrayOfLength':
Check.Quick (Prop.forAll (arrayOfLength 2) (fcheck f2))
works as expected, however:
Check.Quick (Prop.forAll (Generators.arb_params) (fcheck f2))
just starts doing some calculation and never comes back. f# gurus please help.
I did not try this, but I think the problem is that the generator creates float values randomly and then checks whether they match the predicate you specified (the range). This means that it has to generate a large number of floats before it (randomly) generates one that matches.
It would be easier to generate values in a specified range by generating float values in a range [0 .. 1]
and then re-scaling them to match the range you need.
I'm not familiar with FsCheck enough, so I don't know if there is a generator for [0 .. 1] floating-point range, but you could start by generating integers and transforming them to floats:
let gen_doublein mx mn = gen {
let! n = Arb.generate<int>
let f = float n / float Int32.MaxValue
return mx + (f * (mn - mx)) }
EDIT I see that you solved the problem already. I think the solution I posted might still be relevant for smaller ranges (where the random generator does not produce enough matching values soon enough).
The problem was the parameters were the wrong way round. Tomas's suggestion is a good one, and there are some helper functions to implement it.
// Another id function
let fd (d:double) = d
// Check that it is in bounds
let mn=1.0
let mx=5.0
let fdcheck d = (fd d <= mx) && (fd d >= mn)
// Run the check with the numbers generated within the bounds
Check.Quick (Prop.forAll (Arb.fromGen (Gen.map (fun x->
match x with
| _ when Double.IsNaN x -> (mn+mx)/2.0
| _ when x> 1e+17 ->mx
| _ when x< -1e17 ->mn
| _ -> mn + (mx-mn)*(sin x+1.0)/2.0
) Arb.generate<double>
)
) fdcheck
)
Here I have a function which passes the test if the parameter is generated correctly. I'm not sure Tomas's idea with integers works because I think that a lot of small integers are generated and so the doubles don't explore the domain much - but maybe somebody who knows FSCheck might enlighten us.
Rewritten a sample from #b1g3ar5 this way
let mapRangeNormal (min : float<_>, max : float<_>) x =
match x with
| _ when Double.IsNaN x -> (min + max) / 2.0
| _ when Double.IsPositiveInfinity x -> max
| _ when Double.IsNegativeInfinity x -> min
| _ -> min + (max - min) * (sin x + 1.0) / 2.0
let mapRangeUniform (min : float<_>, max : float<_>) x =
match x with
| _ when Double.IsNaN x -> (min + max) / 2.0
| _ when Double.IsPositiveInfinity x -> max
| _ when Double.IsNegativeInfinity x -> min
| _ when x < 0.0 ->
let newRange = max - min
min - x * (newRange / Double.MaxValue) - newRange / 2.0
| _ -> let newRange = max - min
min + x * (newRange / Double.MaxValue) + newRange / 2.0

Resources