I am completely new to F# (started using it today) and relatively new to functional programming (I have minor experience with Lisp). I want to exit a function by returning a value when a certain condition is met so that the rest of the loop is not executed. Here is a C# illustration of what I want to do:
bool CheckRow (int n, int i)
{
for(int j = 0; j < 9; j++)
if (n == sudoku[i][j])
return false;
return true;
}
I tried implementing the same function in F# like this (sudoku is an array2D):
let CheckRow (n : int) (i : int) : bool =
for j = 0 to 8 do
if (n = sudoku.[i, j]) then
false
true
However, I get the following error at false within the if: "This expression was expected to have type unit but here has type bool". What is the proper way to "return" from within a F# function?
To leave a function u can simply use return. Big boss, break and continue are used in loops and statements. if you include any loop in your function, then you can use either break or continue, else use return.
break is used to exit (escape) the for -loop, while -loop, switch -statement that you are currently executing. return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
return always leaves the currently executed function (optionally with a return value) break leaves the currently executed loop. continue skips all remaining statements in the current loop and continues with the next iteration.
break is used to end a loop prematurely while return is the keyword used to pass back a return value to the caller of the function. If it is used without an argument it simply ends the function and returns to where the code was executing previously.
Higher-order functions are nice of course, but at some point someone has to write a loop (e.g. to implement the higher-order function), and that'll eventually be you, so it's nice to know how to write loops in F#. There is no early return from a for
loop in F#, but other types of loops do allow this:
// While loop, imperative style
let checkRow n i =
let mutable clear = true
let mutable j = 0
while clear && j < 9 do
clear <- n <> sudoku.[i, j]
j <- j + 1
clear
// Tail-recursive style - more idiomatic F#
let checkRow n i =
let rec loop j =
if j = 9 then true
elif sudoku.[i, j] = n then false
else loop (j + 1)
loop 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With