Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value to break function

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?

like image 255
CuriouS Avatar asked Nov 22 '16 13:11

CuriouS


People also ask

Can you return break from a 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.

Is return equal to break?

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).

Is return 0 the same as break?

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.

Can we use break after return in Python?

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.


1 Answers

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
like image 138
Asik Avatar answered Oct 04 '22 15:10

Asik