# HG changeset patch # User IBBoard # Date 1561903823 -3600 # Node ID 83b4f23b9df8342b9f4e01d9ce79d0225d802469 # Parent eb868f089bd1ec40c5bfb4288910b2fbc6f35934 First successful attempt at a Haskell monad for hashtable lookup diff -r eb868f089bd1 -r 83b4f23b9df8 7-Haskell/day3.hs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/7-Haskell/day3.hs Sun Jun 30 15:10:23 2019 +0100 @@ -0,0 +1,32 @@ +-- Monad tutorials: +-- * https://wiki.haskell.org/All_About_Monads +-- * https://www.haskell.org/tutorial/monads.html +-- +-- Pre-existing monads: https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#g:2 + +module Day3 where + -- Build a "hash" table (actually a simple lookup in a key-value list, because hashes are hard) + hashtable = [ + ("Phonetic", [ + ("Latin", [ + ("alpha", "a"), + ("beta", "b"), + ("charlie", "c") + ]), + ("Greek", [ + ("alpha", "α"), + ("beta", "β"), + ("gamma", "γ") + ]) + ]) + ] + + -- Note: We've got to put the key first so that we can call it in-fix and supply the search key + -- Note 2: The input value has to be a "Just x" otherwise we can "Couldn't match type 'Maybe' with []" + -- Note 3: I can't get anything out of this other than "Just ", even if I include ">>= return" + -- Example usage: Just hashtable >>= ht_lookup "Phonetic" >>= ht_lookup "Greek" >>= ht_lookup "alpha" + ht_lookup :: String -> [(String, a)] -> Maybe a + ht_lookup _ [] = Nothing + ht_lookup search_key ((key, value):tail) + | search_key == key = Just value + | otherwise = ht_lookup search_key tail \ No newline at end of file