View Single Post
Old Oct 24th, 2006, 7:16 AM   #5
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by magnus.therning
You need some parentheses around the list pattern
Whoops! You're quite correct!

Quote:
Originally Posted by BungalowBill
I do have another question now though. How would i go about declaring a list? For example a list of tuples like ((Jane,Mary), (Scott,Brian)) which would mean that Jane likes Mary or Scott likes Brian for example. Which i could then use at the terminal like this.
If I've understood you correctly, you want a hashtable of some kind. You can do this one of two ways. The most basic way is to define a list of tuples:
relationships = [("Jane", "Mary"), ("Scott", "Brian")]
And then to iterate through the entire list until you find a match. The long way of doing this would be:
inList :: Eq a => a -> [a] -> Bool
inList y (x:xs) = if y == x then True else (inList y xs)
inList y []     = False

likes a b xs = inList (a, b) xs

main = print (likes "Scott", "Brian", relationships)
Or you could do it using any:
likes a b xs = any (== (a, b)) xs
However, a more efficient way of doing this would be to use a set. As far as I'm aware, there isn't a standard set module for Haskell, but any decent Haskell implementation should have one in the standard library. For instance, GHC has Data.Set:
import Data.Set as Set

relationships = Set.fromList [("Jane", "Mary"), ("Scott", "Brian")]

likes a b s = Set.member (a, b) s
Because we're using a data type designed for this sort of work, the above allows for more efficient lookups than the standard iterative model.
Arevos is offline   Reply With Quote