我必须向我的Haskell代码中添加什么才能处理所有情况



我的代码不起作用,例如: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]

您的模式匹配做得太多了。您可以使用三种模式:

  1. 空列表
  2. 非空列表,其中第一子列表具有两个或多个项目;以及
  3. 非空列表,其中第一个列表包含少于两个项目

因此,您可以将其定义为:

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

最新更新