[Haskell-beginners] Wrapping random

Torsten Otto t-otto-news at gmx.de
Fri Nov 28 16:53:32 EST 2008

Hi all,

I teach a high school class in Computer Science. The current  
programming goal is to implement chat-bots, and we're using Haskell of  
course. Now one of my students had the seemingly easy idea of having  
the bot answer with a random sentence if it doesn't have "good" answer.

Random in Haskell has its problems. I understand why you can't just  
call a function as you would in Java. I'm not firm enough with monads  
myself (and certainly don't want to go there in the class beyond I/O)  
so I'm calling for help here: Is there a way to wrap the generation of  
random numbers so that for the students it works like a function?

We have this working:

 > import System.Random

 > main =
 >   do randomNumber <- randomRIO (1::Int,2)
 >      print (randomAnswer randomNumber)

 > randomAnswer r
 >	| (r == 1) = "Nope!"
 >	| (r == 2) = "Absolutely!"
 >   | otherwise = "Error!"

Now, how can we use it for something like this:

 >findAnswer [] = "h"
 >findAnswer (x:xs)
 >	| (z == "unknown") = findAnswer xs
 >	| otherwise = z
 >   where z = findWord x lexikon

where instead of getting "h" we'd like to call a function that would  
give us one of the strings out of randomAnswer.
(findAnswer looks through a list [(keyword,response)].

I've looked at realworldhaskell and the wikibook among other sources,  
but I can't manage to piece anything useful together. How do I manage  
to get something of type IO to represent itself as a String?

Any help would be greatly appreciated.

Torsten Otto

More information about the Beginners mailing list