繁体   English   中英

Haskell清单的清单

[英]Haskell list of list's

我想将列表列表中的每个项目与其他元素进行比较,例如,

[[1,2,3], [0,2,2], [1,4,5], [3,1,1]] 

比较[1,2,3]与[0,2,2]并应用一个运算(例如,距离“ sqrt((x2-x1)^ 2 +(y2-y1)^ 2)的公式”和该操作的结果用一个警卫程序对其进行评估),然后将[1,2,3]与[1,4,5]比较,然后结束列表,然后将[0,2.2]与[1,4,5]进行比较等...

我正在考虑进行比较(头i)和尾(头i),但不知道如何继续进行比较

你们能告诉我我该怎么做吗? 谢谢

编辑

我需要的是这个,对于列表的第一个列表,我需要根据距离公式并比较列表的第三个元素来制作列表的另一个列表,例如

    [[1,2,3], [0,2,2], [1,4,5], [3,1,1]] 

     [x1,y1,z1], [x2,y2,z2]
    sqrt ((x2-x1)^2+(y2-y1)^2)) if result_of_sqrt < z1 then 1:[do the same thing with the other element]                    
else 0:[do the same thing with the other element]

sqrt ((0-1)^2+(2-2)^2) ) = 1, 1 < 3 => 1:(compare this two elements [1,2,3],[1,4,5]) and so...

这个问题确实还不清楚,但是听起来,从根本上来说,您想要获取列表中的每个元素并将其与列表中所有其他元素进行比较。 假设我们想将[1..3]中的所有元素配对,顺序无关紧要,即我们想要列表:

`[(1, 2), (1, 3), (2, 3)]`

我们可以直接这样做:

pairAll :: [a] -> [(a, a)]
pairAll [] = []
pairAll (x:xs) = map (\y -> (x, y)) xs ++ pairAll xs

现在pairAll [1..3] == [(1, 2), (1, 3), (2, 3)] 我们可以将配对函数分解为:

doStuffToAll :: (a -> a -> b) -> [a] -> [b]
doStuffToAll _ [] = []
doStuffToAll f (x:xs) = map (f x) xs ++ doStuffToAll f xs

然后pairAll = doStuffToAll (\\xy -> (x, y))

将lambda表达式替换为列表的比较函数(即doStuffWithAll compareLists ),如果我能正确理解您的问题,则应该这样做。

这似乎产生了最后一个示例结果:

f xs = map (\x -> map (test x) xs) xs
  where test a@[x1,y1,z1] b@[x2,y2,z2] = 
          if a == b 
             then 0 
             else if sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2) < z1 
                     then 1 
                     else 0

或使用警卫代替if and else

f xs = map (\x -> map (test x) xs) xs
  where test a@[x1,y1,z1] b@[x2,y2,z2] 
          | a == b    = 0 
          | m < z1    = 1 
          | otherwise = 0
    where m = sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2)

输出:

*Main> f [[0,0,4], [2,4,2], [1,3,5], [3,1,1]]
[[0,0,1,1],[0,0,1,0],[1,1,0,1],[0,0,0,0]]

我不确定我是否正确理解了您,但是也许这可以帮助您找到一些答案:

  1. 配对所有元组
  2. 将“比较”功能应用于这些元组并输出是/否

lol :: [(Int,Int,Int)]
lol =  [(1,2,3), (0,2,2), (1,4,5), (3,1,1)]

-- Use list comprehension to get all your unique pairs
tuples = [(x,y) | x <- lol, y <- lol, x > y]

result = map myCompare tuples

-- myCompare takes a tuple of two 3-vector tuples and does an operation on them
-- It outputs the two vectors it and a True/False
myCompare (x@(x1,y1,z1),y@(x2,y2,z2)) = if ( (x1-x2)^2 + (y1-y2)^2 < (z2-z1)^2 ) then (x,y,True) else (x,y,False)       

输出:

tuples = [((1,2,3),(0,2,2)),((1,4,5),(1,2,3)),((1,4,5),(0,2,2)),((3,1,1),(1,2,3)),((3,1,1),(0,2,2)),((3,1,1),(1,4,5))]

result = [((1,2,3),(0,2,2),False),((1,4,5),(1,2,3),False),((1,4,5),(0,2,2),True),((3,1,1),(1,2,3),False),((3,1,1),(0,2,2),False),((3,1,1),(1,4,5),True)]

暂无
暂无

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

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