Alon Rolnik
Alon Rolnik

Reputation: 873

pattern matching in ML

I have this code:

fun all_except_option2(str : string, strlst : string list) =
    let fun all_except_option([], result) = NONE
    | all_except_option(str::T, result) = SOME(List.rev(result) @ T)
    | all_except_option(H::T, result) =all_except_option(T, H::result)
    in
    all_except_option(strlst, [])
    end

and the compiler says:

hw2provided.sml:22.13-24.70 Error: match redundant (nil,result) => ... (str :: T,result) => ... --> (H :: T,result) => ...

I handle this already with "case of" statement but my question is way the language dont do pattern matching with str (from above) ? why the compiler think str is a like H.

Upvotes: 0

Views: 2238

Answers (1)

pad
pad

Reputation: 41290

When you write

| all_except_option(str::T, result) =

str here is a new binding which shadows the old parameter str. So the second pattern has the same form h::t as the last one.

You can compare a value with parameter str using if/else construct:

fun all_except_option2(str: string, strlst: string list) =
  let 
     fun all_except_option([], result) = NONE
      | all_except_option(h::t, result) = if h = str 
                                          then SOME(List.rev(result) @ t)
                                          else all_except_option(t, h::result)
  in
     all_except_option(strlst, [])
  end

Upvotes: 2

Related Questions