Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Accepting different types and acting accordingly

Tags:

haskell

Lets say I got the following very basic example:

f :: Either Int String -> IO ()

as well as a function g :: Int -> IO () and a function g' :: String -> IO () and I basically want to implement f as a "selector" which calls g or g' depending on its input, so that in the future I only have to work with f because I know that my program will only encounter either Int or String.

Does this way of using Either make sense? The convention seems to be to use it mainly for Error and Exception handling.

If it does make sense, what would be a good way or best practice to implement such an example? I've heard/read about case as well as bifunctors.

If it does not: what is the haskell way of handling the possibility of different input types? Or is this something which should be avoided from the beginning?

like image 427
Jessica Nowak Avatar asked Dec 08 '15 12:12

Jessica Nowak


1 Answers

So that definitely can make sense and one way to implement that is:

f :: Either Int String -> IO ()
f e =
    case e of
        Left l -> g l
        Right r -> g' r

or using either:

import Data.Either (either)
f :: Either Int String -> IO ()
f = either g g'

Note that in the second version I don't assign a variable name to the Either Int String argument. That is called eta conversion / eta reduction. But obviously you could also write f e = either g g' e.

like image 168
Johannes Weiss Avatar answered Sep 29 '22 13:09

Johannes Weiss