这是一个递归解决方案。
- 弹出列表的第一个元素(
x
)。
- 使用
partition
到列表中的其余部分分割成是相当于x
(group
)元素和元素不相当于x
(others
)。
x:group
是我们发现的第一个组,然后我们递归others
。
import Data.List (partition)
equivalent :: (a -> a -> Bool) -> [a] -> [[a]]
equivalent eq = go
where
go [] = []
go (x:xs) =
let (group, others) = partition (eq x) xs
in (x:group) : go others
证明使用:
>>> import Data.Function (on)
>>> equivalent ((==) `on` (`mod` 3)) [1..10]
[[1,4,7,10],[2,5,8],[3,6,9]]
顺便说一句,这里是另一种方式来完成同样的事情,我怀疑是速度快:
>>> fmap (fmap snd) . groupBy ((==) `on` fst) . sort . fmap (\i -> (i `mod` 3, i)) $ [1..10]
[[3,6,9],[1,4,7,10],[2,5,8]]
你有什么试过?什么地方出了错? –
我尝试从[1 ... 10]中提取两个值并尝试使用函数eq进行等价判断,但我不知道如何将具有两个参数的函数传递给'filter'。 – notfounds
我误解了'Eq',我会重新思考。 – notfounds