I am new to Haskell and wondered if there was a simple way of creating a data structure that I can add records to through successive function calls, and not lose the state of the structure in between function calls (persistent?), without the need for a database. So I have:
data Book = Book { title :: String
, author :: String
, ISBN :: String
}
deriving (Eq, Show)
type BookShelf = [Book]
I appreciate that Haskell's approach to doing this is to copy the data structure and return an update whenever one attempts to do something like this. So this would work something like:
addToBookShelf :: Book -> BookShelf -> BookShelf
addToBookShelf b bs = b : bs
So I could call this recursively from some other function to fill up BookShelf. I dont believe this will work for me as I am attempting to add records via a JSON PUT request, and I dont want to return the updated list for the function to be called recursively by an external HTTP client?? I'm sure there must be a simple answer to this!
Additional info: I'm using Web.Scotty to parse JSON POST/GET.
You will need to model the state somehow. Since you are new, let's go for a simple way: add a parameter to your server that keeps track of the state:
getBookViaJSON :: IO Book
-- listen, convert, ...
server :: BookShelf -> IO ()
server bookshelf = do
book <- getBookViaJSON
server (book:bookshelf)
This function never returns and never does anything with the bookshelf, so it's not useful in its own right, but you get the idea?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With