> Erlang中文手册 > partition/2 根据断言划分列表

lists:partition/2

根据断言划分列表

用法:

partition(Pred, List) -> {Satisfying, NonSatisfying}

内部实现:

-spec partition(Predicate, List) -> {Satisfying, NotSatisfying} when
      Pred :: fun((Elem :: T) -> boolean()),
      List :: [T],
      Satisfying :: [T],
      NotSatisfying :: [T],
      T :: term().

partition(Pred, L) ->
    partition(Pred, L, [], []).

partition(Pred, [H | T], As, Bs) ->
    case Pred(H) of
	true -> partition(Pred, T, [H | As], Bs);
	false -> partition(Pred, T, As, [H | Bs])
    end;
partition(Pred, [], As, Bs) when is_function(Pred, 1) ->
    {reverse(As), reverse(Bs)}.

根据断言 Predicate 来把列表 List 划分 Satisfying 和 NotSatisfying 2 个列表,Satisfying 列表里的元素是被断言 Predicate 调用返回 true 的元素,而 NotSatisfying 则是被断言 Predicate 调用返回 false 的元素

Predicate = fun(E) -> E rem 2 == 0 end,
lists:partition(Predicate, [1, 2, 3, 4, 5, 6, 7, 8]).