[英]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]]
我不確定我是否正確理解了您,但是也許這可以幫助您找到一些答案:
。
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.