Hi Yotam,

A type variable `a` means that you know absolutely nothing about the variable, and can't treat it specially. So you can't special-case your function to "either Foo or Bar."

You can achieve your goal like this:

func :: Either Foo Bar -> (Int -> Int)
func (Left (Foo a _)) = a
func (Right (Bar a)) = a


The kind of runtime type inspection you might be used to from other langauges is available via the Typeable class. It's extremely non-idiomatic Haskell, and I strongly recommend against writing this sort of code. For completeness, this also works:

func :: Typeable a => a -> Maybe (Int -> Int)
func a = maybeFoo <|> maybeBar
  where
    maybeFoo = case cast a of
      Just (Foo a _) -> Just a
      Nothing -> Nothing
    maybeBar = case cast a of
      Just (Bar a) -> Just a
      Nothing -> Nothing

Matt Parsons

On Tue, Oct 10, 2017 at 10:56 AM, Yotam Ohad <yotam2206@gmail.com> wrote:
Hello cafe,
I am trying to do the following:

data Foo = Foo { a1 :: Int -> Int, a2 :: Int -> Char }
data Bar = Bar { a1 :: Int -> Int }

func :: a -> Maybe (Int -> Int) -- a is either Foo or Bar
func (x::(Bar/Foo) = Just $ a1 x
func _ = Nothing

I'm not sure how to implement this. All I know that the types are matching so I think it could be possible.

Thanks for your help
-Yotam

_______________________________________________
Haskell-Cafe mailing list
To (un)subscribe, modify options or view archives go to:
http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
Only members subscribed via the mailman list are allowed to post.