从列表中获取元组并将其用作Map键

时间:2013-05-22 01:24:57

标签: haskell

我是Haskell的新手,我正在尝试使用Map.fromList。我定义了以下data类型:

type No = String
data Arco = Arco { de :: No
                 , para :: No
                 , custo :: Float
                 } deriving (Show, Ord, Eq)

我有一个Arco列表,我希望使用(de, para)元组作为键来映射它们,并使用custo作为值。我怎样才能做到这一点?

由于

2 个答案:

答案 0 :(得分:3)

我认为您可以使用折叠函数或列表映射来实现此目的,首先将Arco值列表转换为简单列表,然后使用Map.fromList从密钥列表构建映射/值对。某些事情(未经测试):

Map.fromList (foldr (\x res -> ((de x, para x), custo x):res) [] yourArcoList)

map

Map.fromList $ map (\x -> ((de x, para x), custo x)) yourArcoList

或列表理解:

[((de x, para x), custo x) | x <- yourArcoList]

deparacusot是由Haskell为您自动创建的函数,以便您可以从类型值中提取字段值。

答案 1 :(得分:1)

如果有帮助,这里有明确的递归:

type No = String
data Arco = Arco { de :: No
                 , para :: No
                 , custo :: Float
                 } deriving (Show, Ord, Eq)

my_func xs = helper xs []
       where helper [] acc = reverse acc
             helper (x:xs) acc = let key = (de x, para x)
                                     val = custo x
                                 in helper xs ( (key, val):acc )



ghci>:l 1.hs

ghci>let a = Arco "hello" "world" 3.0
ghci>let b = Arco "goodbye" "mars" 10.0

ghci>let list = my_func [a, b]
ghci>list
[(("hello","world"),3.0),(("goodbye","mars"),10.0)]

ghci>import qualified Data.Map as M
ghci>let map = M.fromList list
ghci>map
fromList [(("goodbye","mars"),10.0),(("hello","world"),3.0)]
ghci>M.lookup ("hello", "world") map
Just 3.0