我有一个列表(第一个数字是 id 矩形,第二个数字是宽度矩形,第三个数字是高度矩形):

[Rectangle 1 33 33, Rectangle 2 23 45, Rectangle 3 34 56]

如何更改 id = 2 的宽度和高度矩形?我不知道如何实现函数 modifyRectangle。

我的代码:
modifyRectangle :: [RectangleType] -> Int -> Int -> Int -> IO [RectangleType]
modifyRectangle [] _ _ _ = return []
modifyRectangle x idRectangle new_width new_height = do
    let (Rectangle id width height) = fromJust (findRectangle idRectangle x)
    -- what next ???????
    return x

findRectangle :: Int -> [RectangleType] -> Maybe RectangleType
findRectangle _ [] = Nothing
findRectangle n ((Rectangle id width height) : xs) =
    if n == id then Just (Rectangle id width height)
    else findRectangle n xs

data RectangleType = Rectangle Int Int Int deriving(Show, Read)

addRectangle :: RectangleType -> [RectangleType] -> [RectangleType]
addRectangle x [] = [x]
addRectangle x xs = x:xs

最佳答案

您无法修改它,您只能制作具有不同值的副本。

对此有许多方法,您可以过滤掉原始矩形并添加一个新矩形(不会保持顺序)或将函数映射到原始列表上,该列表返回传入的矩形,除非 id 匹配,在这种情况下返回新的矩形。

关于list - 如何更改列表中的元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5763100/

10-13 05:24