Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I change element on the list?

Tags:

list

haskell

I have a list (first number is id rectangle, second number is width rectangle, third number is height rectangle):

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

How can I change width and height rectangle with id = 2 ? I don't know how I can implement function modifyRectangle.

My code:

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
like image 225
mrquestion Avatar asked Jan 24 '26 08:01

mrquestion


1 Answers

You can't modify it, you can just make a copy with different values.

there are a number of approches to this, you could filter out the original rectangle and add a new one (won't keep order) or map a function over the original list that returns the passed in rectangle unless the id matches, in which case the new rectangle is returned.

like image 162
Tom Avatar answered Jan 26 '26 23:01

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!