[英]Haskell List comprehension and `group`
input:输入:
funcA [((0,'x'),1),((0,'y'),3), ((1,'y'),3),((1,'z'),3) ,((2,'x'),2),((2,'y'),2)] funcA [((0,'x'),1),((0,'y'),3), ((1,'y'),3),((1,'z'),3) , ((2,'x'),2),((2,'y'),2)]
output输出
[(0, 1, "x"), (0, 3, "y"), (1, 3, "yz") , (2, 2, "xy")] [(0, 1, "x"), (0, 3, "y"), (1, 3, "yz") , (2, 2, "xy")]
I'm trying to group by starting node and destination node and then concat
all the edge names(values such as 'x'
, 'y'
...).我正在尝试通过起始节点和目标节点进行分组,然后concat
所有边名称(诸如'x'
、 'y'
... 之类的值)。 So the output order is [(start, end, "concat val"), ...]
所以输出顺序是[(start, end, "concat val"), ...]
How can I write the funcA
in the Haskell language??如何用 Haskell 语言编写funcA
?
I tried groupBy
, List comprehension, map
function in it but couldn't figure it out.我尝试了groupBy
,列表理解,其中的map
功能,但无法弄清楚。
You could define funcA
as:您可以将funcA
定义为:
import Data.Function (on)
import Data.List (groupBy)
funcA :: Eq a => [((a,b),a)] -> [(a,a,[b])]
funcA =
map (\s@(((x,y),_):_) -> (x, y, map snd s))
. groupBy ((==) `on` fst)
. map (\((x,v),y) -> ((x,y),v))
Given the list: [((0,'x'),1),((0,'y'),3),((1,'y'),3),((1,'z'),3),((2,'x'),2),((2,'y'),2)]
给定列表: [((0,'x'),1),((0,'y'),3),((1,'y'),3),((1,'z'),3),((2,'x'),2),((2,'y'),2)]
The map
at the end of the chain joins the coordinates into a tuple:链末端的map
将坐标连接成一个元组:
[((0,1),'x'),((0,3),'y'),((1,3),'y'),((1,3),'z'),((2,2),'x'),((2,2),'y')]
The groupBy
groups on coordinates: groupBy
在坐标上分组:
[[((0,1),'x')],[((0,3),'y')],[((1,3),'y'),((1,3),'z')],[((2,2),'x'),((2,2),'y')]]
The first map
combines characters with the same coordinate to strings with that coordinate.第一个map
将具有相同坐标的字符组合为具有该坐标的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.