Try Finally statement in F# - f#

I am new to learning F# and writing a simple console application, where the user enters a value for distance, and I want some validation to make sure that the input is a number. It also needs to make sure that it is a number, and if it isn't, tell the user and they start again. This is what I have so far:
let distance = 0
while distance = 0 do
System.Console.WriteLine("How far do you want to travel?")
let answer = System.Console.ReadLine()
try
let distance = System.Int32.Parse(answer)
if distance < 0 then
let distance = 0
printfn "Can't use negative numbers"
elif distance = 0 then
printfn "Can't travel a distance of 0"
else
printfn "You are about to travel %A" distance
finally
let distance = 0
printfn "Invalid distance format"
And this is what comes up:
In this example, what I want to happen is for the "Invalid distance format" to not appear, and it moves on to the next part of the app.
How would I make it so that "Invalid distance format" only appears if distance can't be converted to an int via System.Int32.Parse(answer)
Even if try-finally is the complete wrong way to go about doing this, how else would it be done?
Thanks in advance

What you want is try...with
try
let distance = System.Int32.Parse(answer)
. . . . .
with
| _ as ex -> printfn "Invalid Distance Format"
http://fsharpforfunandprofit.com/posts/exceptions/
You could also do something like
...
let attemptedConvert = Int32.TryParse(answer)
let success,convertValue = attemptedConvert
if success then
//other stuff here
else
printfn "Invalid Number Format"
This way there is no exception thrown, and you still have validation if the entry was converted successfully.
As noted below, exceptions can be a more expensive operation than other alternatives, and should be evaluated to see if that is causing unnecessary overhead. Like any process though, this should be evaluated on a case by case basis.
TryParse Method

As you are learning, I would approach this problem by doing something like this.
It makes use of the option type which is useful for handling the 'null' case (i.e. no input). It also uses F#s pattern matching, which is a very powerful alternative to using if, else, elif etc.
//see here - http://fsharpforfunandprofit.com/posts/the-option-type/
let tryParseOption intStr =
try
let i = System.Int32.Parse intStr
Some i
with _ -> None
type Ask =
static member Askdistance (?text)=
let text = defaultArg text ""
printfn "%s" text
System.Console.WriteLine("How far do you want to travel?")
let distance = tryParseOption (System.Console.ReadLine())
match distance with
|None -> Ask.Askdistance("Invalid format distance provided")
|Some(a) when a <0 -> Ask.Askdistance("Can't use negative numbers")
|Some(a) when a =0 -> Ask.Askdistance("Can't travel a distance of 0")
|_ -> printfn "You are about to travel %A" distance.Value
ignore()
//this will keep asking you to input a distance until you put in a correct value (i.e. a positive integer value. Note it will reject a floating point input).
Ask.Askdistance()

While the other answers are correct, here is another way of doing it:
open System
let rec travel() =
printfn "How far do you want to travel?"
let d = Console.ReadLine()
match Int32.TryParse d with
| false, _ ->
printfn "Invalid distance format '%s'" d
travel()
| _, 0 ->
printfn "Can't travel a distance of 0"
travel()
| _, d when d < 0 ->
printfn "Can't use negative number %i" d
travel()
| _, d ->
printfn "You are about to travel %i" d
travel()
In my opinion, this has the following advantages:
does not use exceptions
does not use different concepts for the same thing (printfn vs Console.WriteLine)
does not introduce unnecessary constructs (types, helper functions for already existing functionality)
does not mix responsibilities (print error of this invocation in the next one)
I agree, that learning a new language you should explore the solution space. But then choose a concise, elegant way.
Some other aspects of my answer may be opinionated though. You might want to
use explicit trues instead of _.
choose a different name for the matched, parsed distance. I use shadowing because I think of the parsed value as just being a different representation.
reorder the cases, e.g. having the 'happy path' first resembles a try...catch:
open System
let rec travel() =
printfn "How far do you want to travel?"
let d = Console.ReadLine()
match Int32.TryParse d with
| true, d when d > 0 ->
printfn "You are about to travel %i" d
| true, 0 ->
printfn "Can't travel a distance of 0"
travel()
| true, _ ->
printfn "Can't use negative number %i" d
travel()
| _ ->
printfn "Invalid distance format '%s'" d
travel()
travel()
Another approach would be to separate reading from the console and traveling:
using a reading function which always returns an int:
open System
let rec readInt() =
let d = Console.ReadLine()
match Int32.TryParse d with
| true, d ->
d
| _ ->
printfn "Invalid distance format '%s'" d
readInt()
let rec travel() =
printfn "How far do you want to travel?"
let d = readInt()
if d > 0 then
printfn "You are about to travel %i" d
elif d = 0 then
printfn "Can't travel a distance of 0"
travel()
else
printfn "Can't use negative number %i" d
travel()
travel()
using a reading function that might fail:
open System
let rec readInt() =
let d = Console.ReadLine()
match Int32.TryParse d with
| true, d -> Some d
| _ -> None
let rec travel() =
printfn "How far do you want to travel?"
match readInt() with
| Some d when d > 0 ->
printfn "You are about to travel %i" d
| Some d when d = 0 ->
printfn "Can't travel a distance of 0"
travel()
| Some d ->
printfn "Can't use negative number %i" d
travel()
| None ->
printfn "Invalid distance format '%s'" d
travel()
travel()

Related

Return the condition in the fitler?

I have the following code to filter a Seq and return the error if nothing returned.
let s = nodes
|> Seq.filter(fun (a, _, _, _) -> if a.ToLower().Contains(key1)) // condition 1
then true
else false // Error message should have Key1
|> Seq.filter(....) // condition 2
|> Seq.filter(....) // condition 3
.....
|> Seq.filter(function // condition N
| _, Some date, _, _ -> date >= StartPeriod
| _ -> false // put StartPeriod in the final message s is not empty before this step
)
if Seq.isEmpty s
then sprintf "Failed by condition 1 (%s) or condition 2 (%s) .... or condition N (Date > %s)"
key1, ...., (StartPeriod.ToShortDateSTring())
else ....
The final error message sprintf will contain all the filter conditions. Is it a way to let the code just return the ones (or just the last one) make the s empty?
Based on rmunn's answer, I modified it to return all the filters that contributed to empty the list.
let rec filterSeq filterList input msgs =
match filterList with
| [] -> input, msgs
| (label, filter) :: filters ->
let result = input |> Seq.filter filter
if result |> Seq.isEmpty then
printfn "The \"%s\" filter emptied out the input" label
Seq.empty, (List.append msgs [label])
else
filterSeq filters result (List.append msgs [label])
let intFiltersWithLabels = [
"Odd numbers", fun x -> x % 2 <> 0
"Not divisible by 3", fun x -> x % 3 <> 0
"Not divisible by 5", fun x -> x % 5 <> 0
"Even numbers", fun x -> x % 2 = 0
"Won't reach here", fun x -> x % 7 <> 0
]
{ 1..20 } |> filterSeq intFiltersWithLabels <| List.empty
What I would do is make a list of filters, and a recursive function that applies them one at a time. If the filter that was just applied returns an empty sequence, then stop, print the filter that just emptied your input, and return that empty sequence. Otherwise keep looping through the recursive function, taking the next filter in the list in turn, until either you end up with no input or you have run through your entire filter list and there's still some input remaining after passing all the filters.
Here's some sample code to illustrate what I mean. Notice how I've put labels in front of each filter function, so that I don't see output like "The <fun:filtersWithLabels#4> filter emptied out the input", but instead I see a sensible human-readable label for each filter.
let rec filterSeq filterList input =
match filterList with
| [] -> input
| (label, filter) :: filters ->
let result = input |> Seq.filter filter
if result |> Seq.isEmpty then
printfn "The \"%s\" filter emptied out the input" label
Seq.empty
else
filterSeq filters result
let intFiltersWithLabels = [
"Odd numbers", fun x -> x % 2 <> 0
"Not divisible by 3", fun x -> x % 3 <> 0
"Not divisible by 5", fun x -> x % 5 <> 0
"Even numbers", fun x -> x % 2 = 0
"Won't reach here", fun x -> x % 7 <> 0
]
{ 1..20 } |> filterSeq filtersWithLabels
// Prints: The "Even numbers" filter emptied out the input
If you want to print all filters until the one that emptied out the input, then you'd just move that printfn call up one line, outside the if expression. The fact that the recursion stops once the input is empty means that you won't see any printfn calls after the filter that emptied out the input.
Note that the way I wrote the function assumes that your original input will not be empty. If your original input was empty, then the function will credit the first filter for emptying the input and will print the first filter's label. You could solve that easily enough by checking for empty input before you check for empty result, but I didn't bother since this is just demo code. Just be aware of this if your real input could ever be empty in your actual use case.
Update: If you need to return a list of labels, not just print them, then make that a second parameter that you pass through your filterSeq function. Something like this:
let matchingFilters filterList input =
let rec filterSeq filterList labelsSoFar input =
match filterList with
| [] -> input, [] // Note NO labels returned in this case!
| (label, filter) :: filters ->
let result = input |> Seq.filter filter
if result |> Seq.isEmpty then
Seq.empty, (label :: labelsSoFar)
else
filterSeq filters (label :: labelsSoFar) result
let result, labels = filterSeq filterList [] input
result, List.rev labels
let filtersWithLabels = [
"Odd numbers", fun x -> x % 2 <> 0
"Not divisible by 3", fun x -> x % 3 <> 0
"Not divisible by 5", fun x -> x % 5 <> 0
"Even numbers", fun x -> x % 2 = 0
"Won't reach here", fun x -> x % 7 <> 0
]
{ 1..20 } |> matchingFilters filtersWithLabels
// Returns: ["Odd numbers"; "Not divisible by 3"; "Not divisible by 5"; "Even numbers"]
A couple things to note about this version of the function: it sounds like what you want is that if the filters run all the way through without emptying out the input, then you want NO filter labels to be returned. If I've misunderstood you, then replace the | [] -> input, [] line with | [] -> input, labelsSoFar to get all the labels in the output. Second thing to note is that I've changed the "shape" of this function: instead of returning a seq, it returns a 2-tuple of (result seq, list of filter labels). The list of filter labels will be empty if the result seq is not empty, but if the result seq ended up empty, then the list of filter labels will contain all the filters that were applied, not just all the filters that reduced the size of the input.
If what you really need is to check whether the size of the input is reduced and print only the labels of filters that filtered something out, then look at Funk's answer for how to check that, but be aware that Seq.length has to run through the entire original sequence and apply all the filters up to that point, each time. So it's a slow operation. If your input data set is large, then it's best to stick with the Seq.empty logic. Play around with it and decide what best fits your needs.
You can separate your logging / error handling code from your business logic by using a decorator.
First, our logger.
open System.Text
type Logger() =
let sb = StringBuilder()
member __.log msg =
sprintf "Element doesn't contain %s ; " msg |> sb.Append |> ignore
member __.getMessage() =
sb.ToString()
Now, we want to wrap Seq.filter so it logs every time we filter out some element(s).
let filterBuilder (logger:Logger) msg f seq =
let res = Seq.filter f seq
if Seq.length seq > Seq.length res then logger.log msg
res
Wrapping up with an example.
let logger = Logger()
let filterLog msg f seq = filterBuilder logger msg f seq
let seq = ["foo" ; "bar"]
let r =
seq
|> filterLog "f"
(fun s -> s.Contains("f"))
|> filterLog "o"
(fun s -> s.Contains("o"))
|> filterLog "b"
(fun s -> s.Contains("b"))
|> filterLog "a"
(fun s -> s.Contains("a"))
logger.getMessage()
val it : string = "Element doesn't contain f ; Element doesn't contain b ; "
"bar" gets filtered out immediately, producing the first message. "foo" goes out the third time around. Also note the second and last pipe in the line don't log any message.

Initialize function with standard input

I am facing a problem that leave me disoriented, since it should be a pretty basic procedure. I am learning how to build simple console applications with F#, but I cannot figure out how to pass an integer as standard input to the program. Please consider:
open System
let square x = x * x
[<EntryPoint>]
let main (argv :string[]) =
printfn "The function will take an input and square it"
printfn "%d squared is %d" 12 (square 12)
Console.ReadLine() |> ignore
0
How can I pass the value to printfn and square the way I can do in C with:
int main(){
int i;
scanf("%d", &i);
printf("\nThe value of variable i is %d.\n", i);
return 0;
}
I tried to adapt let x = Console.ReadLine() to get integers, but no appreciable results. The documentation I consulted, mainly consider string inputs. I am afraid I am missing something important for properly comprehend the basic of F#. Any suggestion, in this sense, would be highly appreciated.
ReadLine () will return a string. As mentioned by #JohnPalmer, it needs to be parsed to an int. The following program should give you the basic idea:
let rec input () =
printf "Input: "
match Core.int.TryParse (stdin.ReadLine ()) with
| true, i -> i
| _ ->
printfn "Invalid input, try again"
input ()
let square x = x * x
[<EntryPoint>]
let main _ =
printfn "The function will take an input and square it"
let i = input ()
printfn "%d squared is %d" i (square i)
0

Which match with indentation rule is at play here?

This indentation works fine:
match 5 with
| k when k < 0 ->
"value is negative"
| k -> "value is non-negative"
|> printfn "%s"
but this does not:
match 5 with
| k when k < 0 ->
"value is negative"
| k ->
"value is non-negative"
|> printfn "%s"
Which F# indentation rule is at play?
This is a combination of indentation under match and special case for operators.
First, under match, the body of each case can start as far left as the vertical line. For example, this works:
match 5 with
| x ->
"some value"
Second, there is a special offset rule for operators that appear at the beginning of a new line: such operators can be to the left of the previous line up to the width of the operator plus one. For example, these all work identically:
let x =
"abc"
|> printf "%s"
let y =
"abc"
|> printf "%s"
let z =
"abc"
|> printf "%s"
So, in your second example, the second case of the match includes the printfn line, because the forward pipe operator is within the acceptable tolerance to the left from the beginning of the first line.
If you move the string "value is non-negative" just two spaces to the right, the forward pipe won't be within the tolerance anymore, and so the printfn line will be interpreted as being outside the match.
match 5 with
| k when k < 0 ->
"value is negative"
| k ->
"value is non-negative"
|> printfn "%s"
In your first example, it is moved 5 spaces to the right, so that works too.

How do i write the classic high/low game in F#?

I was reading up on functional languages and i wondered how i would implement 'tries' in a pure functional language. So i decided to try to do it in F#
But i couldnt get half of the basics. I couldnt figure out how to use a random number, how to use return/continue (at first i thought i was doing a multi statement if wrong but it seems like i was doing it right) and i couldnt figure out how to print a number in F# so i did it in the C# way.
Harder problems is the out param in tryparse and i still unsure how i'll do implement tries without using a mutable variable. Maybe some of you guys can tell me how i might correctly implement this
C# code i had to do last week
using System;
namespace CS_Test
{
class Program
{
static void Main(string[] args)
{
var tries = 0;
var answer = new Random().Next(1, 100);
Console.WriteLine("Guess the number between 1 and 100");
while (true)
{
var v = Console.ReadLine();
if (v == "q")
{
Console.WriteLine("you have quit");
return;
}
int n;
var b = Int32.TryParse(v, out n);
if (b == false)
{
Console.WriteLine("This is not a number");
continue;
}
tries++;
if (n == answer)
{
Console.WriteLine("Correct! You win!");
break;
}
else if (n < answer)
Console.WriteLine("Guess higher");
else if (n > answer)
Console.WriteLine("Guess lower");
}
Console.WriteLine("You guess {0} times", tries);
Console.WriteLine("Press enter to exist");
Console.ReadLine();
}
}
}
The very broken and wrong F# code
open System;
let main() =
let tries = 0;
let answer = (new Random()).Next 1, 100
printfn "Guess the number between 1 and 100"
let dummyWhileTrue() =
let v = Console.ReadLine()
if v = "q" then
printfn ("you have quit")
//return
printfn "blah"
//let b = Int32.TryParse(v, out n)
let b = true;
let n = 3
if b = false then
printfn ("This is not a number")
//continue;
//tries++
(*
if n = answer then
printfn ("Correct! You win!")
//break;
elif n < answer then
printfn ("Guess higher")
elif n>answer then
printfn ("Guess lower")
*)
dummyWhileTrue()
(Console.WriteLine("You guess {0} times", tries))
printfn ("Press enter to exist")
Console.ReadLine()
main()
Welcome to F#!
Here's a working program; explanation follows below.
open System
let main() =
let answer = (new Random()).Next(1, 100)
printfn "Guess the number between 1 and 100"
let rec dummyWhileTrue(tries) =
let v = Console.ReadLine()
if v = "q" then
printfn "you have quit"
0
else
printfn "blah"
let mutable n = 0
let b = Int32.TryParse(v, &n)
if b = false then
printfn "This is not a number"
dummyWhileTrue(tries)
elif n = answer then
printfn "Correct! You win!"
tries
elif n < answer then
printfn "Guess higher"
dummyWhileTrue(tries+1)
else // n>answer
printfn "Guess lower"
dummyWhileTrue(tries+1)
let tries = dummyWhileTrue(1)
printfn "You guess %d times" tries
printfn "Press enter to exit"
Console.ReadLine() |> ignore
main()
A number of things...
If you're calling methods with multiple arguments (like Random.Next), use parens around the args (.Next(1,100)).
You seemed to be working on a recursive function (dummyWhileTrue) rather than a while loop; a while loop would work too, but I kept it your way. Note that there is no break or continue in F#, so you have to be a little more structured with the if stuff inside there.
I changed your Console.WriteLine to a printfn to show off how to call it with an argument.
I showed the way to call TryParse that is most like C#. Declare your variable first (make it mutable, since TryParse will be writing to that location), and then use &n as the argument (in this context, &n is like ref n or out n in C#). Alternatively, in F# you can do like so:
let b, n = Int32.TryParse(v)
where F# lets you omit trailing-out-parameters and instead returns their value at the end of a tuple; this is just a syntactic convenience.
Console.ReadLine returns a string, which you don't care about at the end of the program, so pipe it to the ignore function to discard the value (and get rid of the warning about the unused string value).
Here's my take, just for the fun:
open System
let main() =
let answer = (new Random()).Next(1, 100)
printfn "Guess the number between 1 and 100"
let rec TryLoop(tries) =
let doneWith(t) = t
let notDoneWith(s, t) = printfn s; TryLoop(t)
match Console.ReadLine() with
| "q" -> doneWith 0
| s ->
match Int32.TryParse(s) with
| true, v when v = answer -> doneWith(tries)
| true, v when v < answer -> notDoneWith("Guess higher", tries + 1)
| true, v when v > answer -> notDoneWith("Guess lower", tries + 1)
| _ -> notDoneWith("This is not a number", tries)
match TryLoop(1) with
| 0 -> printfn "You quit, loser!"
| tries -> printfn "Correct! You win!\nYou guessed %d times" tries
printfn "Hit enter to exit"
Console.ReadLine() |> ignore
main()
Things to note:
Pattern matching is prettier, more concise, and - I believe - more idiomatic than nested ifs
Used the tuple-return-style TryParse suggested by Brian
Renamed dummyWhileTrue to TryLoop, seemed more descriptive
Created two inner functions doneWith and notDoneWith, (for purely aesthetic reasons)
I lifted the main pattern match from Evaluate in #Huusom's solution but opted for a recursive loop and accumulator instead of #Hussom's (very cool) discriminate union and application of Seq.unfold for a very compact solution.
open System
let guessLoop answer =
let rec loop tries =
let guess = Console.ReadLine()
match Int32.TryParse(guess) with
| true, v when v < answer -> printfn "Guess higher." ; loop (tries+1)
| true, v when v > answer -> printfn "Guess lower." ; loop (tries+1)
| true, v -> printfn "You won." ; tries+1
| false, _ when guess = "q" -> printfn "You quit." ; tries
| false, _ -> printfn "Not a number." ; loop tries
loop 0
let main() =
printfn "Guess a number between 1 and 100."
printfn "You guessed %i times" (guessLoop ((Random()).Next(1, 100)))
Also for the fun of if:
open System
type Result =
| Match
| Higher
| Lower
| Quit
| NaN
let Evaluate answer guess =
match Int32.TryParse(guess) with
| true, v when v < answer -> Higher
| true, v when v > answer -> Lower
| true, v -> Match
| false, _ when guess = "q" -> Quit
| false, _ -> NaN
let Ask answer =
match Evaluate answer (Console.ReadLine()) with
| Match ->
printfn "You won."
None
| Higher ->
printfn "Guess higher."
Some (Higher, answer)
| Lower ->
printfn "Guess lower."
Some (Lower, answer)
| Quit ->
printfn "You quit."
None
| NaN ->
printfn "This is not a number."
Some (NaN, answer)
let main () =
printfn "Guess a number between 1 and 100."
let guesses = Seq.unfold Ask ((Random()).Next(1, 100))
printfn "You guessed %i times" (Seq.length guesses)
let _ = main()
I use an enumeration for state and Seq.unfold over input to find the result.

Block following this 'let' is unfinished. Expect an expression

Hi everbody I am doing a project with F# but I get this error when ı use let num= line for the following code . I'm new at F# so I can not solve the problem. My code should do this things. User enter a number and calculate the fibonacci but if user enter not a number throw exception
open System
let rec fib n =
match n with
|0->0
|1->1
|2->1
|n->fib(n-1)+fib(n-2);;
let printFibonacci list =
for i=0 to (List.length list)-1 do
printf "%d " (list.Item(i));;
let control = true
while control do
try
printfn "Enter a Number:"
let num:int = Convert.ToInt32(stdin.ReadLine())
with
| :? System.FormatException->printfn "Number Format Exception";
let listFibonacci = [for i in 0 .. num-1->fib(i)]
printFibonacci(listFibonacci)
printfn "\n%A"(listFibonacci)
control<-false
Console.ReadKey(true)
exit 0;;
I'm not an F# expert but I can see 3 problems with the code you posted.
1) As Lasse V Karlsen commented - f# uses the 'offside' rule so your 'fib' expression needs the body indented in. If you are running this in the Visual Studio Shell it should warn you of this by putting a blue squiggly line under the appropriate code.
2) Both 'control' and 'num' are mutable values so need to be declared explicitly as such.
f# is a functional language so by default any expressions are immutable i.e they are not allowed to change state after they have been declared.
In f#, saying 'let n = expr' does not mean 'assign the value of expr to n' like you would in say c# or c++. Instead it means 'n fundamentally is expr' and will be forever much like a mathematical equation.
So if you want to update the value of a variable you use the special '<-' notation which is the equivalent of 'assign the value on rhs to the lhs' and you need to declare that variable as mutable i.e 'this value can be changed later'
So I think both num and control need to be declared at the top of the loop as
let mutable control = false
let mutable num = 0 // or whatever you want the initial value of num to be
As a side note you don't have to explicitly declare num as an int ( you can if you want ) but f# will infer the type for you
If I understand your code correctly, you want to keep asking for input number n until a valid number is given and print fibonacci numbers up to n. In this case, you'd better move the calculation and printing inside the try block. Here's an updated version with formatting.
open System
let rec fib n =
match n with
|0->0
|1->1
|2->1
|n->fib(n-1)+fib(n-2);;
let printFibonacci list =
for i=0 to (List.length list)-1 do
printf "%d " (list.Item(i))
let mutable control = true //you forgot to add the 'mutable' keyword
while control do
try
printfn "Enter a Number:"
let num:int = Convert.ToInt32(stdin.ReadLine())
let listFibonacci = [for i in 0 .. num-1 -> fib(i)]
printFibonacci(listFibonacci)
printfn "\n%A"(listFibonacci)
control <- false
with
| :? System.FormatException -> printfn "Number Format Exception"
//add the ignore statement to drop the resulting ConsoleKeyInfo struct
//or the compiler will complain about an unused value floating around.
Console.ReadKey(true) |> ignore
// exit 0 (* Exit isn't necessary *)
Instead of using an imperative style number entry routine and relying on exceptions for control flow, here's a recursive getNumberFromConsole function you could use as well:
open System
let rec fib n =
match n with
| 0 -> 0
| 1 | 2 -> 1
| n -> fib(n-1) + fib(n-2);;
let printFibonacci list =
for i=0 to (List.length list)-1 do
printf "%d " (list.Item(i))
//alternative number input, using recursion
let rec getNumberFromConsole() =
match Int32.TryParse(stdin.ReadLine()) with
| (true, value) -> value
| (false, _) -> printfn "Please enter a valid number"
getNumberFromConsole()
printfn "Enter a Number:"
let num = getNumberFromConsole()
let listFibonacci = [for i in 0 .. num-1 -> fib(i)]
printFibonacci(listFibonacci)
printfn "\n%A"(listFibonacci)
Console.ReadKey(true) |> ignore
P.S. Thanks for showing me stdin. I never knew it existed. Now I can write some interactive scripts.

Resources