SML How to check variable type?

后端 未结 2 728
说谎
说谎 2021-02-20 12:01

Is there any way to check/test the type of a variable?

I want to use it like this:

if x = int then foo
else if x = real then bar
else if x = string then          


        
2条回答
  •  广开言路
    2021-02-20 12:25

    ML languages are statically typed, so it's not possible for something to have different types at different times. x can't sometimes have type int and at other times have the type string. If you need behavior like this, the normal way to go about it is to wrap the value in a container that encodes type information, like:

    datatype wrapper = Int of int | Real of real | String of string
    

    Then you can pattern-match on the constructor:

    case x of Int x    -> foo
            | Real x   -> bar
            | String x -> ...
    

    In this case, x is clearly typed as a wrapper, so that will work.

提交回复
热议问题