Displaying a list of different types that implement the same function?

I want to apply a function to each element in the list (map), but the elements can have different types, but all implement the same function (here "putOut") as the interface. However, I can’t create a list of this type of "interface" (here is "Output").

How to compare the list of different types that implement the same function?

import Control.Monad

main :: IO ()
main = do
 mapM_ putOut lst
 where
  lst :: [Outputable] -- ERROR: Class "Outputable" used as a type
  lst = [(Out1 1),(Out2 1 2)]

class Outputable a where
 putOut :: a -> IO ()

-- user defined:

data Out1 = Out1 Int deriving (Show)
data Out2 = Out2 Int Int deriving (Show)

instance Outputable Out1 where
 putOut out1 = putStrLn $ show out1

instance Outputable Out2 where
 putOut out2 = putStrLn $ show out2
+3
source share
2 answers

Haskell does not allow heterogeneous lists. Thus, you can not make Outputables list because of your Out1, and Out2are two different types, even if they both belong to the same type.

, ExistentialQuantification. . Haskell wikibook.

  • {-# LANGUAGE ExistentialQuantification #-}

  • , :

      data ShowBox = forall s. Show s => SB s
      heteroList :: [ShowBox]
      heteroList = [SB (), SB 5, SB True]
    
  • :

      instance Show ShowBox where
        show (SB s) = show s
    
  • .

:

{-# LANGUAGE ExistentialQuantification #-}

main :: IO ()
main = do
 mapM_ print lst
 putStrLn "end"
 where
  lst :: [Printable]
  lst = [P (Out1 1),P (Out2 1 2)]

-- box type (2)
data Printable = forall a . Show a => P a

-- necessary Show instance for the box type (3)
instance Show Printable where show (P x) = show x

-- user defined:
data Out1 = Out1 Int deriving (Show)
data Out2 = Out2 Int Int deriving (Show)
+10

?

- jetxee , , : , , , - putOut, IO (). , "" , . , ? - :

main :: IO ()
main = do
    sequence_ lst
    where lst :: [IO ()]
          lst = [out1 1, out2 1 2]

out1 x = putStrLn $ unwords ["Out1", show x]
out2 x y = putStrLn $ unwords ["Out2", show x, show y]

, Haskell. :

  • - , show, unwords, & c. , IO.
  • IO () - , .. sequence_ main.

" show" -. - Eq, , , , - . , , - , , ( ) Bool .


, Haskell OOP. ad-hoc-, . , , ad-hoc-, , , .., ; Haskell ( ) .

, , (, ) , , (this, self, ..). Haskell, :

  • " " self, .
  • ""

; . - , , .

, ; - , , .

, - Monad, , , OOP, #, , - IMonad.

. , , . Graphics.DrawingCombinators , , .

+7

Source: https://habr.com/ru/post/1750482/


All Articles