Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell IO can't get the list to loop around a menu function

Tags:

io

haskell

I'm currently making a text based menu system in haskell. I have made a data type called Book where each function edits the list and returns it. However I cannot work out how to make a menu part work where it can edit this list and recurse back around.

Example on what I'm stuck on menu works, add a book to the list, menu then needs to reload the menu so I can display the books with the new addition.

example of menu

menu:: [Book] -> [IO]
menu books = do
  str <- getLine
  let selectNum = (read str :: Int)
  case selectNum of
     1 -> let sd = addNewBookIO books 
     2 -> displayAllBooksFromYear books

example of adding a new book

addNewBookIO :: [Book] -> IO [Book]
addNewBookIO films =
  do putStr "Film name: " 
     filmTitle <- getLine
     putStr "List all cahr in the Book (separated by commas): "
     cast <- addToStringArray []
     putStr "Year of Realese in the UK: "
     year <- getLine
     let test = (read year :: Int)
     putStr "List all the fans(separated by commas): "
     fans <- addToStringArray [] 
     putStrLn "Your Book has been added"
     let bookList = addbookFilm (Film bookTitle cast test fans) films
     return bookList

Any help would be grateful

like image 870
Fred Jones Avatar asked Sep 19 '25 01:09

Fred Jones


1 Answers

At the moment your type signature for menu doesn't make any sense. Do you mean something like this?

menu :: [Book] -> IO [Book]

If so, then you could define it to be

menu books = do
  str <- getLine
  case read str of
    1 -> do books' <- addNewBookIO books             -- add a new book, then loop
            menu books'
    2 -> displayAllBooksFromYear books >> menu books -- display books, then loop
    3 -> return books                                -- quit

This reads a string from the user, and then either adds a new book, displays the current list of books or ends the loop, returning the list of books.

Edit: The >> operator sequences two operations together. The combination a >> b means "do a, then do b".

The following two pieces of code are exactly equivalent (in fact, the first one is just syntactic sugar for the second)

do displayAllBooksFromYear books
   menu books

and

displayAllBooksFromYear books >> menu books

Hope that helps clear things up.

like image 125
Chris Taylor Avatar answered Sep 20 '25 22:09

Chris Taylor