SML How to check variable type?

后端 未结 2 769
说谎
说谎 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:45

    It's not possible to do what you want in general, even if x is of polymorphic type (without doing the wrapping yourself as Chuck suggests).

    This is a deliberate design decision; it makes it possible to make very strong conclusions about functions, just based on their types, that you couldn't make otherwise. For instance, it lets you say that a function with type 'a -> 'a must be the identity function (or a function that always throws an exception, or a function that never returns). If you could inspect what 'a was at runtime, you could write a sneaky program like

    fun sneaky (x : 'a) : 'a = if x = int then infinite_loop() else x
    

    that would violate the rule. (This is a pretty trivial example, but there are lots of less-trivial things you can do by knowing your type system has this property.)

提交回复
热议问题