I’ve written following codes:
class Number a where
compareN :: [a] -> [(String,String,Int)]
type Name = String
type Nr = Int
data N = Nums Name Nr
compareNum :: N -> N -> Int
compareNum (Nums a b) (Nums c d) = abs(b-d)
nameOfNum :: N -> String
nameOfNum (Nums a b) = a
instance Number N where
compareN [] = []
compareN [nr] = [(a,b,c) | a <- [nameOfNum nr], b <- [nameOfNum nr], c <- [compareNum nr nr]]
When I try to run with:
compareN [(Nums "one" 1),(Nums "two" 2)]
I got error msg:
* Exception: test.hs:(18,9)-(19,101): Non-exhaustive patterns in function compareN
The anwser I want to get is like this:
[("one","one",0),("one","two",1),("two","one",1),("two","two",0)]
I know I have to write one more pattern:
compareN (nr:nrs) = [(a,b,c) | a <- [nameOfNum nr], b <- [nameOfNum nr], c <- [compareNum nr nr] : (compareN nrs)]
But it’s not working.. Any help pls! Thx
You use pattern matching as if you tried to do a manual recursion, but in the same moment you do a strange list comprehension. Here is a cleaner approach. The first step generates all permutations of the two numbers and the second does the comparisons:
The syntax
a <- xs, b <- xsmeans, that the output consists of all possible ways to take anaand abfromxs; no pattern matching is needed here.