Search code examples
haskelltypestype-systems

Case between two unrelated types in Haskell


Is it possible to use case expression between two unrelated types in Haskell, like in this example (not working) code:

data A = A
data B = B

f x = case x of
  A -> 1
  B -> 2

main = do
  print $ test A
  return ()

I know I can use Either here, but this code is not meant to be used - I want to deeply learn the Haskell type system and see what could be done.


Solution

  • A and B are distinct types. If you want a function that can take values of multiple types, you need a typeclass.

    data A = A
    data B = B
    
    class F a where
      f :: a -> Int
    
    instance F A where
      f _ = 1
    
    instance F B where
      f _ = 2
    
    main = do
      print $ f A