Re:Why isn't Haskell popular in industry?
by jrockway on Monday August 02, 2010 @06:01AM
(#1567278)
The Maybe and List monads have nothing to do with state, and are very
common in programs.
Let's use the List monad to determine someone's roommates.
> import Control.Applicative
> import Data.List
First, the data:
> type Person = String
> type Address = String
> addresses :: [(Person, Address)]
> addresses = [("jrockway", "123 Fake St."), ("jrockway's cat", "123 Fake St.")]
> people :: [(Address, Person)]
> people = uncurry (flip (,)) <$> addresses
And some helper functions around this data, a function to return all
addresses for a person, and a function to return all people that live
at a certain address:
> assocFilter :: Eq a => a -> [(a,b)] -> [b]
> assocFilter p xs = snd <$> filter ((==p) . fst) xs
> addressesForPerson person = assocFilter person addresses
> peopleAtAddress address = assocFilter address people
To find a person's roommate, we have to chain two computations.
First, we have to find zero or more places where a person lives. Then
we need to find who else lives at each of those addresses. With the
List monad, this is not much code!
> roommatesFor :: Person -> [Person]
> roommatesFor person = do
> address <- addressesForPerson person
> peopleAtAddress address
The monadic combinator >>= (which is hidden by do) does all the looping for us, so we don't have to explicitly write it out.
BTW, you can just cut-n-paste this into a .lhs file and run it, if you want to try it out.
Let's use the List monad to determine someone's roommates.
First, the data: And some helper functions around this data, a function to return all addresses for a person, and a function to return all people that live at a certain address: To find a person's roommate, we have to chain two computations. First, we have to find zero or more places where a person lives. Then we need to find who else lives at each of those addresses. With the List monad, this is not much code! The monadic combinator >>= (which is hidden by do) does all the looping for us, so we don't have to explicitly write it out.BTW, you can just cut-n-paste this into a .lhs file and run it, if you want to try it out.