我的代码不起作用,例如:swapElems ([],[1,2])
我该怎么修?
swapElems :: [[a]] -> [[a]]
swapElems [] = []
swapElems [x:y:xs] = [y : x :xs]
swapElems ((x:y:s):ls) = (y:x:s): swapElems ls
swapElems [x]= [x]
您的模式匹配做得太多了。您可以使用三种模式:
- 空列表
- 非空列表,其中第一子列表具有两个或多个项目;以及
- 非空列表,其中第一个列表包含少于两个项目
因此,您可以将其定义为:
swapElems :: [[a]] -> [[a]]
swapElems [] = … -- (1)
swapElems ((x:y:xs):xss) = … -- (2)
swapElems (xs:xss) = … -- (3)
然而,实现一个助手函数可能更有意义:
swap2 :: [a] -> [a]
swap2 (x:y:xs) = …
swap2 xs = xs
然后使用swap2
:的映射
swapElems :: [[a]] -> [[a]]
swapElems =mapswap2