简体   繁体   English

无法使用Haskell数据结构中的列表

[英]Cannot cons to a list in Haskell data structure

The code below has a data structure Bot which has a parameter values of type [Int]. 下面的代码具有一个数据结构Bot,该数据结构的参数值类型为[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. 函数GiveValue从哈希图中检索给定索引的漫游器,将值添加到该漫游器的values参数中,并返回更新后的哈希图。 However, it currently replaces the existing Int in values, rather than append to the array. 但是,当前它替换现有的Int值,而不是追加到数组。 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 . 我认为您的意思是bot = getBot botInd oldM而不是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. 编译器可能已经捕捉到了这一点,只是您将Int用作要输入的值的类型以及查找机器人的方式。

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? 也许,如果您改为将整个Bot传递给giveValue ,那么您可以确定是否为正确的机器人赋予了正确的价值?

You could also wrap the "bot id" in a newtype, like newtype BotId = BotId { unBotId :: Int } . 您还可以将“机器人ID”包装为新类型,例如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! getBot需要一个BotId ,然后ghc会抱怨您传递的是整数而不是id!

Also, consider using Maybe Int instead of Int for low and high . 另外,请考虑使用Maybe Int代替lowhighInt The fact that you're using a falseVal is a big red flag that you should be using Maybe instead. 您正在使用falseVal的事实是一个大的红旗,您应该改为使用Maybe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM