Functions to Polymorphic data types

后端 未结 3 1878
青春惊慌失措
青春惊慌失措 2021-01-13 12:37

data Foo a is defined like:

data Foo a where
  Foo :: (Typeable a, Show a) => a -> Foo a
  -- perhaps more constructors

instance Show a =         


        
3条回答
  •  甜味超标
    2021-01-13 13:10

    Perhaps you want to omit the type parameter from Foo.

    data Foo where
      Foo :: (Typeable a, Show a) => a -> Foo
    
    instance Show Foo where
      show (Foo a) = show a
    
    fiveFoo :: Foo
    fiveFoo = Foo (5 :: Int) -- (Foo 5) doesn't work because of ambiguity
    
    falseFoo :: Foo
    falseFoo = Foo False
    
    getFoo :: String -> Foo
    getFoo "five" = fiveFoo
    getFoo "false" = falseFoo
    
    print $ getFoo "five" -- prints '5'
    print $ getFoo "false" -- prints 'False'
    

提交回复
热议问题