2
\$\begingroup\$

I'm learning F# and I'm trying the following exercise (exercise 4.10 of Functional Programming Using F#).

Declare an F# function prefix: 'a list -> 'a list -> bool when a:equality. The value of the expression prefix[x_0;x_1;...;x_m] [y_0;y_1;...;y_n] is true if m<=n and x_i=y_i for 0<=i<=m, and false otherwise.

I wanted to use pattern matching on the two inputs, but wasn't sure how to do this with a curried function (as opposed to a function taking a 2-tuple). So I wrote:

let rec prefix a b = (function
    | ([], _) -> true
    | (_, []) -> false
    | (x0::xst,y0::yst) -> x0 = y0 && prefix xst yst) (a,b);;

I wasn't very happy with this, because I thought it would be better (clearer and more efficient) if the inner function called itself, so I tried declaring the inner function locally.

let prefix a b =
    let rec prefixt = function
        | ([], _) -> true
        | (_, []) -> false
        | (x0::xst,y0::yst) -> x0 = y0 && prefixt (xst,yst)
    prefixt (a,b);;

Is this the right way to approach such a problem in F#?

\$\endgroup\$
1
\$\begingroup\$

You can use the match … with … syntax:

let rec prefix a b =
    match (a, b) with
    | ([], _) -> true
    | (_, []) -> false
    | (x0::xst,y0::yst) -> x0 = y0 && prefix xst yst
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.