将Int列表转换为HASKELL中的自定义类型

x33g5p2x  于 2022-11-14  发布在  其他
关注(0)|答案(2)|浏览(123)

我不确定我的方法是否正确,
我想做的是转换一个Int的列表,例如:
[[1234, 5, 2], [4568, 7, 3], [7897, 6, 5]]
成一列[[Patient]]
data Patient = Patient { patientId :: Int, patientTemps :: Int, patientPriorite :: Int } deriving (Show)
我之所以这样做,是因为我想打印“index patientId patientPriorite“,类似于:
1 1234 2
2 4568 3
3 7897 5
所以我想如果我能得到[[Patient]],我就能很容易地访问列表中的元素。

0pizxfdo

0pizxfdo1#

这是一个简单的方法,但如果有任何无效数据(长度为/= 3的列表),则会引发错误。

data Patient = Patient { patientId :: Int, patientTemps :: Int, patientPriorite :: Int } deriving (Show)

main :: IO ()
main = do
  let lists = [[1234, 5, 2], [4568, 7, 3], [7897, 6, 5]]
  print $ map (\[a, b, c] -> Patient a b c) lists

输出量:

[Patient {patientId = 1234, patientTemps = 5, patientPriorite = 2},Patient {patientId = 4568, patientTemps = 7, patientPriorite = 3},Patient {patientId = 7897, patientTemps = 6, patientPriorite = 5}]

更安全的方法是定义一个将[Int]转换为Maybe Patient的函数,然后根据需要处理无效数据:

import Data.Maybe (catMaybes)

data Patient = Patient { patientId :: Int, patientTemps :: Int, patientPriorite :: Int } deriving (Show)

listToPatient :: [Int] -> Maybe Patient
listToPatient [a, b, c] = Just $ Patient a b c
listToPatient _ = Nothing

main :: IO ()
main = do
  let lists = [[1234, 5, 2], [4568, 7, 3], [7897, 6, 5]]
  print $ map listToPatient lists
  -- Two ways to filter out the Nothing values: `catMaybes` or a list comprehension.
  print $ catMaybes $ map listToPatient lists
  print $ [patient | Just patient <- map listToPatient lists]

输出量:

[Just (Patient {patientId = 1234, patientTemps = 5, patientPriorite = 2}),Just (Patient {patientId = 4568, patientTemps = 7, patientPriorite = 3}),Just (Patient {patientId = 7897, patientTemps = 6, patientPriorite = 5})]
[Patient {patientId = 1234, patientTemps = 5, patientPriorite = 2},Patient {patientId = 4568, patientTemps = 7, patientPriorite = 3},Patient {patientId = 7897, patientTemps = 6, patientPriorite = 5}]
[Patient {patientId = 1234, patientTemps = 5, patientPriorite = 2},Patient {patientId = 4568, patientTemps = 7, patientPriorite = 3},Patient {patientId = 7897, patientTemps = 6, patientPriorite = 5}]```
vnzz0bqm

vnzz0bqm2#

您可以为转换编写如下内容:

f :: [[Int]] -> [Patient]
f [] = []
f ([x,y,z]:zs) = Patient { patientId = x, patientTemps = y, patientPriorite = z}: (f zs)
f _ = undefined

如果只想用index显示数据,那么只需将原始数据与一个整数列表压缩在一起,如下所示:

map (\x -> (fst x,(snd x)!!0, (snd x)!!1)) $ zip [1..] yourlist

也就是说,由于列表项对应于特定的属性,我将选择第一个选项。

相关问题