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 interface.
I tried to make a Haskell version below but fail to meet my purpose.
The point here is xs
has type [Bar]
rather than Foo a => [a]
Do that mean Haskell can not do this and shall I think in another way?
Java
interface Foo {
void bar ();
}
public class Bar1 implements Foo {
@Override
public void bar() {
System.out.println("I am bar 1 class");
}
}
public class Bar2 implements Foo {
@Override
public void bar() {
System.out.println("I am bar 2 class");
}
}
public static void main(String[] args) {
// The major purpose here is having a list
// that contains elements which are sub-type of "Foo"
List<Foo> ys = new ArrayList<Foo>();
Foo e1 = new Bar1();
Foo e2 = new Bar2();
ys.add(e1);
ys.add(e2);
for (Foo foo : ys) {
foo.bar();
}
}
Haskell
class Foo a where
bar :: a -> IO ()
data Bar = Bar1 | Bar2
instance Foo Bar where
bar Bar1 = print "I am Bar1"
bar Bar2 = print "I am Bar2"
--xs :: Foo a => [a]
xs :: [Bar]
xs = [Bar1, Bar2]
main :: IO ()
main = mapM_ bar xs