[Haskell-cafe] Parsers for Text Adventures

Stephen Tetley stephen.tetley at gmail.com
Sun Jan 17 09:02:38 EST 2010


Hello Mark


[ Literate haskell follows... ]

> module Verb where

> import qualified Data.Map as Map
> import Data.Char


> data Verb = Go | Get | Jump | Climb | Give deriving (Show, Read)

I wouldn't use read instead something either a simple function:

> verb :: String -> Maybe Verb
> verb "Go"  = Just Go
> verb "Get" = Just Get
> verb _     = Nothing


Or possible a Map:

> verb2 :: String -> Maybe Verb
> verb2 s = Map.lookup s verb_map

> verb_map :: Map.Map String Verb
> verb_map = Map.fromAscList [ ("Go", Go), ("Get", Get) {- .. -} ]


You could then do more about say case sensitivity - e.g. add ("get",Get) etc
or always convert to upper before querying the map.


> verb3 :: String -> Maybe Verb
> verb3 s = Map.lookup (map toUpper s) verb_map2

> verb_map2 :: Map.Map String Verb
> verb_map2 = Map.fromAscList [ ("GO", Go), ("GET", Get) {- .. -} ]


Best wishes

Stephen


More information about the Haskell-Cafe mailing list