greenoldman
greenoldman

Reputation: 21062

Is it possible to do pattern matching with given value in SML?

In Scala it is possible, so I wonder if this possible in SML as well, consider such code:

fun in_list(elem,coll) =   
  case coll of
      [] => false
    | elem :: tail => true
    | head :: tail => in_list(elem,tail);

In the second line of case I would like to use elem from the arguments, but SML treats it as a placeholder and throw an error on redundant case (the third line).

So -- is it possible to use elem here and if yes, how?

Upvotes: 0

Views: 157

Answers (1)

sepp2k
sepp2k

Reputation: 370112

No, it's not possible. You'll have to use an if:

fun in_list(elem,coll) =   
  case coll of
      [] => false
    | head :: tail =>
        if head = elem
        then true
        else in_list(elem,tail)

Or, in this case, you could also use logical operators instead of an if:

fun in_list(elem,coll) =   
  case coll of
      [] => false
    | head :: tail =>
        head = elem orelse in_list(elem,tail)

Upvotes: 3

Related Questions