Home > front end >  trouble understanding calling an F# function
trouble understanding calling an F# function

Time:11-11

I'am quite new to F#, and was solving some basic exercises when i stumbled upon this function

  1. Give the (most general) types of g1 and g2 and describe what each of these two functions computes. Your description for each function should focus on what it computes, rather than on individual computation steps
    let rec g1 p = function 
    | x::xs when p x -> x :: g1 p xs
    | _ -> [];;

i don't the understand " when p x " part, or how to call the function. can someone please explain what this function takes in as an argument? as just calling the function like that " g1 [1;2;3] " gives me an error.

Tried calling the function, and tried reading some text books to figure it out

CodePudding user response:

The function keyword is a bit tricky, but it's just syntactical sugar for a match expression. The following two functions are equivalent:

let fooMatch x = 
    match x with
    | 1 -> "one"
    | _ -> "not one"

let fooFunction =
    function 
    | 1 -> "one" 
    | _ -> "not one"

If you use function instead of match, then the (last) argument to the function becomes implicit, rather than explicit, but it's still there. Both versions of foo take one argument.

The when p x -> part is called a guard. In your case, p stands for "predicate" (a function that returns true/false). To call your function, you need pass both a predicate and a list. E.g. g1 (fun x -> x % 2 = 0) [1;2;3].

CodePudding user response:

so this is clearly homework, so I don't want to answer it in full just give guidance.

let rec g1 p = function 
    | x::xs when p x -> x :: g1 p xs
    | _ -> [];;

is tricky because "function" is sort of shorthand sort of hides a parameter, the above is the same as (well almost, but for your purposes it is).

let rec g1 p ys = 
    match ys with
    | x::xs when p x -> x :: g1 p xs
    | _ -> [];;

so you can immediately see g1 is a function that takes 2 parameters and returns something

g1 : ? -> ? -> ?

you just need to try and work out if there is anything more you can infer anythng about the ?s.

So F# will look at your implementation and try and infer what it can.

as said by brian, "when p x" is a guard, so p is a function that takes an x and returns a bool

p : ? -> bool

and p is the first param of g1 so

g1 : (? -> bool) -> ? -> ?

etc.

  • Related