Haskell函数用于计算列表的子列表

时间:2016-10-25 18:44:50

标签: haskell

有人可以向我解释这个haskell代码是什么意思吗?

sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs

我知道这个函数计算给定列表的子列表。但是,我想知道它是如何工作的。

1 个答案:

答案 0 :(得分:1)

sublists :: [a] -> [[a]]
sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs

--  ghci> sublists [1,2,3] 
--  [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]

--    (each sublist l1 in (sublists [2 , 3])
--      
--      (1 : l1)) 
--        concat (sublists [2, 3])
--
--       sublists [2, 3] = 
--         (each sublist l2 in (sublists [3])
--           (2 : l2)) 
--             concat (sublists [3]) 
--
--             sublists [3] = 
--                 (3 : []) concat [[]]
--                 = [[3], []]
--    
--    now substituting back into the recursion
--        [[2, 3], [2], [3], []]
--    
--    [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]