DEV Community

Discussion on: What's a useful programming language feature or concept that a lot of languages don't have?

Collapse
 
jvanbruegge profile image
Jan van Brügge • Edited

Monads. Seriously! They make composing function so easy: For example you parse a number for a string the user types in (which might fail if the string is not a number), then you want to index a list at that position (which could fail because the list might be shorter) and then you want to print the element at that position out or an error if a previous step failed. In Haskell this looks like this (I added the type signatures of the functions used on top):

readMaybe :: String -> Maybe Int
indexMaybe :: [String] -> Int -> Maybe String
fromMaybe :: String -> Maybe String -> String

myList = ["Hello", "World"]

doStuff :: String -> String
doStuff = fromMaybe "Error" . (readMaybe >=> indexMaybe myList)

main = const getLine >=> putStrLn . doStuff $ ()

Here you see the same function (>=>, which has type Monad m => (a -> m b) -> (b -> m c) -> (a -> m c) btw, so it just composes two monadic functions) used for two completely different contexts: First for the Maybe type and then for doing IO. This is the beauty of Monads (and similar type classes). They provide a unified interface over a great range of types. Once you know how to use Monads in general, you can use it on any type that is a Monad. No more consulting the specific API of the library. Everything has the same API!