[英]convert tuples to a datatype in haskell
我在將具有多個元組的列表轉換為數據類型時遇到問題
data SensorValue = SensorValue {a:: Integer, b:: Integer, c:: [Integer]} deriving (Show)
我的元組列表如下所示:
[(1, [(2, [3,4,5]), (2, [2,3,1]), (3, [2,3,7])]), (2, [(1, [4,4,1]), (2, [2,3,1]), (3, [9,0,3])]),...]
所以基本上我的列表看起來像[(Integer, [(Integer, [Integer])])]
如果我從列表中選取第一個元組(1, [(2, [3,4,5])
那么我的預期輸出是:
具有以下內容的SensorValue對象:
a = 1 -- first element of the first tuple
b = 2 -- first element of the second tuple
c = [3,4,5] -- second element of the second tuple
我知道如何使用fst
到達第一個元組,但是如何到達第二個元組?
您可以在此處使用模式匹配。 您的函數如下所示:
f :: (Integer,[(Integer,[Integer])]) -> [SensorValue]
f (x,((y,z):zs)) = SensorValue x y z : f (x,zs) -- First element same for all
f(x,[]) = []
您仍然需要指定條件來處理其他情況,例如,如果構成外部元組的第二個元素的列表為空,將會發生什么?
列表理解或語法使這很好-假設您理解它們!
doSyntax, listComprehensions :: [(Integer, [(Integer, [Integer])])] -> [SensorValue]
doSyntax sensorPoints = do
(a, pointsAtA ) <- sensorPoints
(b, valuesAtAB) <- pointsAtA
return (SensorValue a b valuesAtAB)
listComprehensions sensorPoints =
[ SensorValue a b valuesAtAB
| (a, pointsAtA ) <- sensorPoints
, (b, valuesAtAB) <- pointsAtA
]
根據您要執行的操作,您甚至可以考慮在結果列表的每個元素中僅存儲一個傳感器值。 像這樣(上面的命名方案有一個變體,只是為了好玩):
data SensorValue = SensorValue { a, b, val :: Integer }
fromRawData abvalM =
[ SensorValue a b val
| (a, bvalM) <- abvalM
, (b, valM) <- bvalM
, val <- valM
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.