Lists of data types: “could not deduce (a ~ SomeType) from the context (SomeTypeclass a)”

后端 未结 3 436
闹比i
闹比i 2021-01-03 22:52

I have the following problem with Haskell\'s type system: I am trying to declare a data type and return a list containing elements of this type from a function. Unfortunatel

3条回答
  •  独厮守ぢ
    2021-01-03 23:31

    Haskell does support heterogenous lists of elements, provided their elements are correctly wrapped (see live code on repl.it):

    {-# LANGUAGE GADTs #-}
    
    -- your sample type
    data SampleType = SampleConstructor
    
    instance Show SampleType where
      show _ = "(SampleType)"
    
    -- MkShowable wrapper
    data Showable where
      MkShowable :: Show a => a -> Showable
    
    instance Show Showable where
      show (MkShowable a) = show a
    
    
    main = do
      let myList :: [Showable]
          myList = [MkShowable SampleConstructor, MkShowable 1, MkShowable True]
      putStrLn $ show myList
      -- ["(SampleType)","1","True"]
    

    See Heterogenous collections for more options.

提交回复
热议问题