Why is there no Show instance for functions?

前端 未结 3 1053
情书的邮戳
情书的邮戳 2020-12-07 02:02

Just a quick conceptual question, I am currently trying to learn and understand Haskell better.

I know the Show function is used to convert values to strings, but wh

3条回答
  •  长情又很酷
    2020-12-07 02:24

    show is the function that is defined on functions that are members of the Show typeclass (if you don't know what a typeclass is, it's kinda like an OOP interface).

    By default, functions are not members of the typeclass, so we can't print them.

    We could make it a member of the typeclass with

    instance Show (a -> b) where
       show f = "Unicorns!!"
    

    but here we realize why it isn't implemented by default. There isn't a simple, obvious representation of functions and haskell doesn't want to guess, and thus no instance.

    The only "permissible" instance would be one that actually prints out the function, but this would require actual language change, ie it would be hardwired into the compiler, which just isn't worth it for the few cases in which it could be useful.

    Further more it's a nontrivial compiler change, Haskell is compiled which means the differences between something like f = g and

    f =             g 
    

    are entirely lost on it. But you'd definitely want that in your function representation. Because of this, you'd have to lug around this string through out the program. This is definitely not what you want in a binary.

    If you really want it to print unicorns!! though, feel free.

提交回复
热议问题