I’m trying to grab a random item from a string list and save that into another string list but I can’t get my code to work.
import System.Random
import Control.Applicative ( (<$>) )
food = ["meatballs and potoes","veggisoup","lasagna","pasta bolognese","steak and fries","salad","roasted chicken"]
randomFood xs = do
if (length xs - 1 ) > 0 then
[list] <- (fmap (xs!!) $ randomRIO (0, length xs -1))
else
putStrLn (show([list])
I’m getting parse error on input ‘<-‘ but I’m sure there are more issues then that. There is also the issue that the list may contain the same dishes two days in a row which is not what I want and I guess I can remove duplicates but that also would remove the number of items in the list which I want to stay the same as the number in the list.
Anyone have a good idea how I could solve this? I have been searching for a day now and I can’t find something useful for me but that’s just because I’m looking in the wrong places. Any suggestion on how I can do this or where I can find the info will be greatly appreciated!
The reason it didn’t work is that you needed another
doafter yourif...then. (After athenyou need an expression, not apattern <- expression.)But that still doesn’t compile, because you don’t actually do anything with your list.
At the end of every
doblock, you need an expression to return.I think you meant to still print some stuff if the length of
xsis too short, and you probably meant to print the selected food if there was more than one to choose from.Better would be:
This
| boolean test =syntax is better for conditional answers based on input.I changed
[list]toitembecause you’re selecting a single item randomly, not a list of items.Haskell is quite happy to let you put
[list], because any string that’s got one character in it matches[list].For example,
"h" = [list]iflist='h', because “h” is short for['h']. Any longer string will give youPattern match failure. In particular, all the food you’ve specified has more than one character, so with this definitionrandomFoodwould never work!itemwill match anything returned by yourrandomRIOexpression, so that’s fine.You imported
<$>then didn’t use it, but it’s a nice operator, so I’ve replacedfmap f iothingwithf <$> iothing.I finally realised I’m doing the wrong thing with short lists; if I do
randomFood ["lump of cheese"]I’ll get["lump of cheese"], which is inconsistent withrandomFood ["lump of cheese"]which will give me"lump of cheese".I think we should separate the short list from the empty list, which enables us to do more pattern matching and less boolean stuff:
This gives three different definitions for
randomFooddepending on what the input looks like.Here I’ve also replaced
putStrLn (show (item))withputStrLn . show $ item– compose the functionsshowandputStrLnand apply ($) that to theitem.