例如,我的代碼不起作用: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]
uj5u.com熱心網友回復:
你的模式匹配做的太多了。您可以使用三種模式:
- 空串列;
- 第一個子串列有兩個或多個專案的非空串列;和
- 一個非空串列,其中第一個串列的專案少于兩個。
因此,您可以將其定義為:
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 = map swap2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517113.html
標籤:哈斯克尔模式匹配
