簡體   English   中英

Haskell按順序將元素添加到元組/列表

[英]Haskell Adding Elements to Tuples/Lists in order

我已經定義了(字符串,整數)對的列表。

 type PatientList = [(String,Int)]

我需要以“名稱”和“數字”的形式將數據添加到此列表,其中,數字將為列表中的每個添加項增加,例如,添加3個名稱后的列表(或元組)如下所示:

 [("bob", 1), ("ted", 2), ("harry", 3)] 

名稱將使用以下代碼捕獲:

  do putStr "You are? "
  name <- getLine

我當前的解決方案是創建一個名稱列表,例如(bob,ted,harry),然后使用zip,將這些列表組合如下:

 zip = [1...]["bob","ted","harry"]

該解決方案無法滿足我的要求,因為我希望在不同時間添加到列表中,並且不能將它們組合在一起。 我怎樣才能做到這一點?

將列表保持反向順序不是更好嗎?

[("harry", 3), ("ted", 2), ("bob", 1)]

比添加要穩定的時間:

add :: PatientList -> String -> PatientList
add [] newName = [newName]
add ((oldName, x):xs) newName = (newName, x+1):(oldName, x):xs

當您需要按順序排列整個列表時,您只需按O(leng yourlist)個線性時間即可:

reverse patientList

您可以使用containers包中的IntMap

import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap

type PatientList = IntMap String

registerPatient :: PatientList -> String -> PatientList
registerPatient pList name
  | IntMap.null plist = IntMap.singleton 1 name  
  | otherwise         = let (n, _) = findMax pList 
                        in IntMap.insert (succ n) name plist

如前所述,如果速度不是問題,則使用長度

add :: String -> [(String, Int)] -> [(String, Int)]
add name xs = xs ++ [(name, length xs)]

但是,如果您刪除一個元素,這會使您的ID混亂,所以也許

add name xs = xs ++ [(name, 1 + ( snd (last xs) ) )]

我沒有嘗試運行任何一種方法,因為我不是使用ghc的計算機,但是您應該明白這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM