Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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#?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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