具有极简变化的工作版本,感谢@Matt、Petr 和 Landei !!!
insert :: (Ord el) => el -> Menge el -> Menge el
insert a (Menge (x:xs)) = ins a (Menge (x:xs)) (Menge [])
ins a (Menge []) (Menge ys) = Menge (ys ++ [a])
ins a (Menge xs@(x:xs')) (Menge ys)
| a < x = Menge (ys ++ [a] ++ xs)
| a > x = ins a (Menge xs') (Menge (ys ++ [x]))
| otherwise = Menge (ys ++ xs)
有一个自己的数据类型 Menge,就像一个列表,我应该在正确的位置插入一个元素......
module Menge (
Menge,
empty,
insert,
ins
) where
data Menge el = Menge [el] deriving (Eq)
instance (Show el) => Show (Menge el) where
show (Menge liste) = "{" ++ (elms liste) ++ "}"
where
elms :: (Show a) => [a] -> String
elms [] = ""
elms (x:[]) = show x
elms (x:xs) = show x ++ ", " ++ elms xs
empty :: Menge el
empty = Menge []
insert :: (Ord el) => el -> Menge el -> Menge el
--insert a (Menge []) = (Menge [a])
insert a (Menge (x:xs)) = ins a (Menge (x:xs)) (Menge [])
ins a (Menge []) (Menge (y:ys)) = (Menge ((y:ys) ++ [a]))
ins a (Menge (x:xs)) (Menge (y:ys))
| a < x = (Menge ((y:ys) ++ [a] ++ (x:xs)))
| a > x = ins a (Menge xs) (Menge ((y:ys) ++ [x]))
| a > x && xs == [] = error "same function as: ins a empty (Menge (y:ys))"
| a == x = (Menge ((y:ys) ++ (x:xs)))
| otherwise = error "blabla"
我输入:insert 2 (Menge ([1,3]))
,在我看来,我应该像这样工作:
--> ins 2 (Menge (1:3)) empty --> 2 > 1 --> ins 2 (Menge [3]) (Menge [] ++ [1])
--> ins 2 (Menge [3]) (Menge [1]) --> 2 < 3 --> (Menge ([1] ++ [2] ++ [3])) --> [1,2,3]
但相反,我得到:“函数 ins 中的非详尽模式”
如果我输入相同的错误:ins 2 (Menge ([1,3])) (Menge [])
,所以第一步工作。似乎编译器不喜欢“empty”/“(Menge [])”,因为如果我输入: ins 2 (Menge ([1,3])) (Menge [1,3])
,我会得到{1, 3, 2}
答案。