comparison 7-Haskell/day3.hs @ 95:83b4f23b9df8

First successful attempt at a Haskell monad for hashtable lookup
author IBBoard <dev@ibboard.co.uk>
date Sun, 30 Jun 2019 15:10:23 +0100
parents
children f548c8460d15
comparison
equal deleted inserted replaced
94:eb868f089bd1 95:83b4f23b9df8
1 -- Monad tutorials:
2 -- * https://wiki.haskell.org/All_About_Monads
3 -- * https://www.haskell.org/tutorial/monads.html
4 --
5 -- Pre-existing monads: https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#g:2
6
7 module Day3 where
8 -- Build a "hash" table (actually a simple lookup in a key-value list, because hashes are hard)
9 hashtable = [
10 ("Phonetic", [
11 ("Latin", [
12 ("alpha", "a"),
13 ("beta", "b"),
14 ("charlie", "c")
15 ]),
16 ("Greek", [
17 ("alpha", "α"),
18 ("beta", "β"),
19 ("gamma", "γ")
20 ])
21 ])
22 ]
23
24 -- Note: We've got to put the key first so that we can call it in-fix and supply the search key
25 -- Note 2: The input value has to be a "Just x" otherwise we can "Couldn't match type 'Maybe' with []"
26 -- Note 3: I can't get anything out of this other than "Just <val>", even if I include ">>= return"
27 -- Example usage: Just hashtable >>= ht_lookup "Phonetic" >>= ht_lookup "Greek" >>= ht_lookup "alpha"
28 ht_lookup :: String -> [(String, a)] -> Maybe a
29 ht_lookup _ [] = Nothing
30 ht_lookup search_key ((key, value):tail)
31 | search_key == key = Just value
32 | otherwise = ht_lookup search_key tail