1

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

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

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

谢谢

4

2 回答 2

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 自动为您创建的函数,以便您可以从类型值中提取字段值。

于 2013-05-22T01:31:49.220 回答
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
于 2013-05-23T02:51:50.490 回答