如何將一個列表拆分爲2個子列表,其中第一個子列表包含來自初始列表開始的元素並等於第一個元素,第二個子列表包含其他元素?我必須解決這個問題,而不使用前奏功能。將Haskell中的列表拆分成子列表
我的基本的解決方案是:
partSameElems :: [a] -> ([a],[a])
partSameElems [] = ([],[])
partSameElems (x:xs) = fstList (x:xs) scdList (x:xs)
where
fstList (x:y:xs) = if x == y then x:y:fstList xs {- I need to do Nothing in else section? -}
scdList (x:xs) = x:scdList xs
例如: [3,3,3,3,2,1,3,3,6,3] -> ([3,3,3,3], [2,1,3,3,6,3])
現在,我可以提供我的版本的解決方案:
partSameElems :: Eq a => [a] -> ([a],[a])
partSameElems [] = ([],[])
partSameElems (x:xs) = (fstList (x:xs), scdList (x:xs))
where
fstList [] _ = []
fstList (x:xs) el = if x == el then x:fstList xs el else []
scdList [] _ = []
scdList (x:xs) el = if x /= el then (x:xs) else scdList xs el
看起來你看起來並不像你在發佈之前嘗試了很多努力。不是學習的好方法。 – Nicolas
@Nicolas我嘗試了一些,現在修復我的«解決方案» – zerospiel