Why is function definition for all types at once not allowed in Haskell?

后端 未结 5 1753
迷失自我
迷失自我 2020-12-10 01:14

This is probably a very basic question, but ...

A function that\'s defined as, say

foo :: a -> Integer

denotes a function from <

5条回答
  •  半阙折子戏
    2020-12-10 01:52

    This question is based on a mistaken premise, Haskell can do that! (although it's usually only used in very specific circumstances)

    {-# LANGUAGE ScopedTypeVariables, NoMonomorphismRestriction #-}
    
    import Data.Generics
    
    q1 :: Typeable a => a -> Int
    q1 = mkQ 0 (\s -> if s == "aString" then 100 else 0)
    
    q2 :: Typeable a => a -> Int
    q2 = extQ q1 (\(f :: Float) -> round f)
    

    Load this and experiment with it:

    Prelude Data.Generics> q2 "foo"
    0
    Prelude Data.Generics> q2 "aString"
    100
    Prelude Data.Generics> q2 (10.1 :: Float)
    10
    

    This doesn't necessarily conflict with answers that claim types have no computational significance. That's because these examples require the Typeable constraint, which reifies types into data values that are accessible during runtime.

    Most so-called generic functions (e.g. SYB) rely on either a Typeable or a Data constraint. Some packages introduce their own alternative functions to serve essentially the same purpose. Without something like these classes, it's not possible to do this.

提交回复
热议问题