How to get the non-named field value of data type in Haskell ? (How to get 'x' 'y' value from Rectangle in gtk2hs?)

StackOverflow https://stackoverflow.com/questions/19715820

  •  02-07-2022
  •  | 
  •  

سؤال

data Rectangle = Rectangle Int Int Int Int (link to gtk2hs-doc)
I don't have any idea to get 'width' or 'height' values from Rectangle.
How to get the non-named field value of data type? Thanks.


For What:

I want to get the size of a widget and tried like this:

main = do
    initGUI
    -- . . . 
    widget <- drawingAreaNew
    canvasArea <- newIORef $ Rectangle 0 0 defaultWidth defaultHeight
    widget `onExpose` updateCanvas widget (liftIO (readIORef canvasArea) >>= render)
    onSizeAllocate widget $ updateSize canvasArea
    -- . . .

updateSize :: IORef a -> a -> IO ()
updateSize old new = writeIORef old new

And noticed that I don't know the way of getting the values...

هل كانت مفيدة؟

المحلول

The principle behind getting those parameters out is pattern matching, like so:

case rect of
  Rectangle x y w h -> "The width is " ++ show w ++ " and the height is " ++ show h

This will assign the width and the height to w and h inside the case expression.

In a specific setting this could possibly be made shorter (by pattern matching directly on the argument to a function, by assigning the rect value to a pattern and so on) but pattern matching like this is the main principle.

نصائح أخرى

Better is to declare Rectangle somewhat different:

data Rectangle = Rectangle { left, top, width, height :: Int }

Then, if r is a Rectangle, you can write width r to get its width.

You can still write Rectangle 100 200 300 400 to create a Rectangle.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top