The code below has a data structure Bot which has a parameter values of type [Int]. The function giveValue retrieves the bot of a given index from a hashmap, adds a value to that bot's values parameter and returns the updated hashmap. However, it currently replaces the existing Int in values, rather than append to the array. Could someone explain to me why this is happening?
import Data.List.Split
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map
data Bot = Bot {values :: [Int], low :: Int, high :: Int}
instance Show (Bot) where
show b = show (values b) ++ " " ++ show (low b) ++ " " ++ show (high b)
getBot :: Int -> Map Int (Bot)-> Bot
getBot i m
| (length bots == 1) = bots !! 0
| otherwise = Bot [] falseVal falseVal
where
falseVal = -1
bots = [b | (i2, b) <- Map.toList m, i2==i]
giveValue :: Int -> Int -> Map Int (Bot) -> Map Int (Bot)
giveValue botInd val oldM = newM
where
bot = getBot val oldM
newM = Map.insert botInd (Bot (val : values bot) (low bot) (high bot)) oldM
main = do
let bot = Bot [17] 3 4
let bots = Map.insert 0 bot (Map.empty)
print $ giveValue 0 61 bots
-- Prints fromList [(0, [12] -1 -1)]
I think you mean bot = getBot botInd oldM
not bot = getBot val oldM
.
The compiler could have caught this, except you're using Int
as the type of both the value you want to put in and how you're looking up the bot.
Maybe if you pass in the whole Bot
to giveValue
instead, then you could be sure that you're giving the right value to the right bot?
You could also wrap the "bot id" in a newtype, like newtype BotId = BotId { unBotId :: Int }
. getBot
would take a BotId
, and then ghc would've complained that you were passing in an integer instead of an id!
Also, consider using Maybe Int
instead of Int
for low
and high
. The fact that you're using a falseVal
is a big red flag that you should be using Maybe
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.