view 7-Haskell/day3.hs @ 99:67631cb2ea48

Expand the last note on getting into the monad state
author IBBoard <dev@ibboard.co.uk>
date Sun, 30 Jun 2019 16:15:33 +0100
parents 58f9c6e20f02
children
line wrap: on
line source

-- 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
-- and https://wiki.haskell.org/All_About_Monads#Introduction_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 []" - this appears to be to start the Maybe monad situation
    --          because "ht_lookup "Phonetic" hashtable" works fine. If we didn't want to "Just" it then we can start with "ht_lookup "Phonetic" hashtable >>= …"
    -- Note 3: I can't get anything out of this other than "Just <val>", even if I include ">>= return"
    -- Example usage: Just hashtable >>= ht_lookup "Phonetic" >>= ht_lookup "Greek" >>= ht_lookup "alpha"
    -- This is monadic because "Just hashtable >>= ht_lookup "Phonetic" >>= ht_lookup "foo" >>= ht_lookup "alpha" >>= return" doesn't explode but returns Nothing
    -- To unwrap, we need something like "fromMaybe "" (Just hashtable >>= ht_lookup "Phonetic" >>= ht_lookup "Greek" >>= ht_lookup "alpha")" which returns the value or the empty string
    -- BUT we need to get our value types to match (and we need to do "import Data.Maybe" first)
    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