Multiple Patterns in 1 case

前端 未结 3 1925
囚心锁ツ
囚心锁ツ 2021-01-18 08:40

In SML, is it possible for you to have multiple patterns in one case statement?

For example, I have 4 arithmetic operators express in string, \"+\", \"-\", \"*

3条回答
  •  深忆病人
    2021-01-18 09:26

    Expanding upon Ionuț's example, you can even use datatypes with other types in them, but their types (and identifier assignments) must match:

    datatype mytype = COST as int | QUANTITY as int | PERSON as string | PET as string;
    
    case item of
      (COST n|QUANTITY n) => print Int.toString n
      |(PERSON name|PET name) => print name
    

    If the types or names don't match, it will get rejected:

    case item of
      (COST n|PERSON n) => (* fails because COST is int and PERSON is string *)
      (COST n|QUANTITY q) => (* fails because the identifiers are different *)
    

    And these patterns work in function definitions as well:

    fun myfun (COST n|QUANTITY n) = print Int.toString n
       |myfun (PERSON name|PET name) = print name
    ;
    

提交回复
热议问题