1.如何计算嵌套在元组中的数量
联合时出现2.got错误,即使嵌套数量相同,如何联合这个元组列表?错误:
<interactive>:13:1:
No instance for (Eq Expr) arising from a use of `union'
Possible fix: add an instance declaration for (Eq Expr)
In the expression: union b1 b2
In an equation for `it': it = union b1 b2
haskell代码:
countnest :: (Int,Int) -> Int
countnest ((a1,a2), (b1,b2)) = max (max ((countnest (fst (a1,a2)))+1) ((countnest (snd (a1,a2)))+1)) (max ((countnest (fst (b1,b2)))+1) ((countnest (snd (b1,b2)))+1))
countnest (a1, (b1,b2)) = max 0 (max ((countnest (fst (b1,b2)))+1) ((countnest (snd (b1,b2)))+1))
countnest ((a1,a2), b1) = max (max ((countnest (fst (a1,a2)))+1) ((countnest (snd (a1,a2)))+1)) 0
countnest (a1, a2) = 1
countnest a1 = 1
rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate n xs = zipWith const (drop n (cycle xs)) xs
rev2 :: [a] -> [a]
rev2 (x:[]) = [x]
rev2 (x:xs) = rev xs ++ [x]
flatten1 :: [[a]] -> [a]
flatten1 xss = foldr (++) [] xss
getUniqueOrder :: (Ord a) => [[a]] -> [[a]]
getUniqueOrder xs = nub ( map sort xs)
getUnique :: (Ord a) => [[a]] -> [[a]]
getUnique xs = nub (xs)
data Expr = A | B | C | D | S | M2 | M1 | MM1 deriving (Show)
let cartProd xs ys = [(x,y) | x <- xs, y <- ys]
let m1 = cartProd [A,S] [B,M2]
let m2 = (cartProd (cartProd (cartProd [A,S] [B,M2]) [C,M1]) [D])
let m3 = m2 ++ [(((S,MM1),MM1),MM1)]
let a1 = m3
let b1 = [rotate y a1 | y <- [0..(length a1 -1)]]
let a2 = rev a1
let b2 = [rotate y a2 | y <- [0..(length a2 -1)]]
union b1 b2
当编译countnest得到错误时,经过多次尝试,仍然不能
找到哪里错了,已经匹配模式
*Main> :l oo.hs
[1 of 1] Compiling Main ( oo.hs, interpreted )
oo.hs:140:12:
Couldn't match expected type `Int'
with actual type `((Int, Int), (Int, Int))'
In the pattern: (a1, a2)
In the pattern: ((a1, a2), (b1, b2))
In an equation for `countnest':
countnest ((a1, a2), (b1, b2))
= max
(max
((countnest (fst (a1, a2))) + 1) ((countnest (snd (a1, a2))) + 1))
(max
((countnest (fst (b1, b2))) + 1) ((countnest (snd (b1, b2))) + 1))
oo.hs:140:21:
Couldn't match expected type `Int'
with actual type `((Int, Int), (Int, Int))'
In the pattern: (b1, b2)
In the pattern: ((a1, a2), (b1, b2))
In an equation for `countnest':
countnest ((a1, a2), (b1, b2))
= max
(max
((countnest (fst (a1, a2))) + 1) ((countnest (snd (a1, a2))) + 1))
(max
((countnest (fst (b1, b2))) + 1) ((countnest (snd (b1, b2))) + 1))
答案 0 :(得分:0)
countnest :: (Int,Int) -> Int
countnest ((a1,a2), (b1,b2)) = ...
此处的函数定义与声明不一致。但这不仅仅是一个错误:你所呼唤的东西&#34; tuple&#34;实际上是一棵树,所以你可能需要这样的代码:
data NestType = ConsLeaf Int | ConsPair NestType NestType
countnest :: NestType -> Int
countnest (ConsLeaf _) = 1
countnest (ConsPair x y) = max (countnest x) (countnest y) +1