How do I make an heterogeneous list in Haskell? (originally in Java)

前端 未结 4 1663
南旧
南旧 2021-02-10 13:13

How to convert following Java implementation into Haskell?

The major purpose here is having a list that contains various elements which are sub-type of a particular in

4条回答
  •  滥情空心
    2021-02-10 14:03

    Your translation has an important drawback. Whereas in your Java version, you could easily add a Bar3 that also supports the Foo interface, you cannot easily achieve the same without touching the Bar type in the Haskell version. So this is rather not the version you are looking for.

    In a way you are looking for a heterogeneous list. Other questions are covering this aspect already.

    What you really want though is to get rid of the need of a type class altogether. Instead have a data type representing the behavior of Foo:

    data Foo = Foo { bar :: IO () }
    

    Then you can construct your list of object satisfying the Foo interface as a [Foo].

提交回复
热议问题