
Hi, I'm having trouble with this small exercise. A function maybeA takes a list of pairs. A pair has a variable 'a' and a value 'b'. If any first element of a pair equals to any first element of another pair, the function returns Nothing. If they aren't equal, the function returns a tuple containing the first variable, its value and the value of the second variable. maybeA :: [(a,b)] -> Maybe (a,b,b) For example: [(a1,b1),(a2,b2),(a3,b3)..] returns Nothing if a2 = a3 and returns Just (a2,b2,b3) if a2 /= a3 I'm currently have :maybeA [(a1,b1),(a2,b2)] |a1 == a2 = Nothing |a1 /= a2 = Just (x1,y1,y2) but it only takes 2 pairs. Any helps? Thanks

Hi Anonymous W!
As list is a recursive datastructure, you need a recursive (or
folding) function to check for duplicates. Right now your function
really does accept only two-element lists.
The function would look something like this:
maybeA list@ ((a1,b1) : (a2,b2) : rest) =
if hasUniqueKeys list
then Just (a1, b1, b2)
else Nothing
where
hasUniqueKeys xs = ... check the list ...
You also need to decide what to do, if the list is empty or contains
only one pair.
Markus Läll
On Thu, Nov 4, 2010 at 12:31 AM, Anonymous W
Hi, I'm having trouble with this small exercise.
A function maybeA takes a list of pairs. A pair has a variable 'a' and a value 'b'. If any first element of a pair equals to any first element of another pair, the function returns Nothing. If they aren't equal, the function returns a tuple containing the first variable, its value and the value of the second variable. maybeA :: [(a,b)] -> Maybe (a,b,b)
For example: [(a1,b1),(a2,b2),(a3,b3)..] returns Nothing if a2 = a3 and returns Just (a2,b2,b3) if a2 /= a3
I'm currently have :
maybeA [(a1,b1),(a2,b2)]
|a1 == a2 = Nothing
|a1 /= a2 = Just (x1,y1,y2)
but it only takes 2 pairs. Any helps?
Thanks
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners

On Thu, Nov 11, 2010 at 06:59:01PM +0200, Markus Läll wrote:
Hi Anonymous W!
As list is a recursive datastructure, you need a recursive (or folding) function to check for duplicates. Right now your function really does accept only two-element lists.
The function would look something like this:
maybeA list@ ((a1,b1) : (a2,b2) : rest) = if hasUniqueKeys list then Just (a1, b1, b2) else Nothing where hasUniqueKeys xs = ... check the list ...
You also need to decide what to do, if the list is empty or contains only one pair.
This is good advice. I would add, however, that I don't think hasUniqueKeys ought to be (directly) recursive. Instead, use functions from the standard libraries to manipulate the list and decide whether it has unique keys. Functions which may be helpful in this task include map, fst, sort, group, length, any. -Brent
participants (3)
-
Anonymous W
-
Brent Yorgey
-
Markus Läll