简体   繁体   English

Elixir:流入跑步

[英]Elixir: Streaming into runs

I'd like to stream a list (pre-sorted) such as 我想一个列表(预先排序),如

[1,1,1,2,2,2,2,2,2,3,3,4] [1,1,1,2,2,2,2,2,2,3,3,4]

so it becomes split into runs like this 所以它会分成这样的运行

[[1,1,1],[2,2,2,2,2,2],[3,3],[ 4]] [[1,1,1],[2,2,2,2,2,2],[3,3],[4]]

is there a neat way of doing this? 这样做有一个简洁的方法吗?

I've been studying: Stream.transform , Stream.take_while , Enum.split_while , Enum.partition , Enum.flat_map_reduce 我一直在研究: Stream.transformStream.take_whileEnum.split_whileEnum.partitionEnum.flat_map_reduce

In the end I need to extend the answer from lists of numbers to tuples that contain numbers 最后,我需要将答案从数字列表扩展到包含数字的元组

I think Enum.chunk_by/2 (there's also a Stream version) does the trick: 我认为Enum.chunk_by/2 (还有一个Stream版本)可以解决这个问题:

iex(1)> [1,1,1,2,2,2,2,2,2,3,3,4] |> Enum.chunk_by(fn(x) -> x end)
[[1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3], [4]]

Or with capture syntax: 或者使用捕获语法:

iex(2)> [1,1,1,2,2,2,2,2,2,3,3,4] |> Enum.chunk_by(&(&1))

I would use Stream.chunk_by : 我会使用Stream.chunk_by

Stream.chunk_by(nums, fn num -> num end) |> Enum.to_list
#> [[1,1,1], [2,2,2,2,2,2], [3,3], [4]]]

Easy! 简单!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM