Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change record values in Haskell

Tags:

haskell

record

I am trying to write a Haskell module with the following code:

module RectangleMover where

data Rectangle = Rectangle { xCoordinate :: Int
                           , yCoordinate :: Int
                           , width :: Int
                           , height :: Int
                           } deriving (Show)

move :: Rectangle -> Int -> Int -> Rectangle
-- Edit 1
move rec x y =
    let rec' = { xCoordinate + x
               , yCoordinate + y
               }
    return rec

To create a rectangle i would type:

let rec = Rectangle 10 10 20 30

But my question is now how to implement a function that "moves" this rectangle? In C# or Java the call would be something like this: rec.move(20,20); But how would this be written in Haskell?

This is unfortunately my first try with a functional programming language...

Edit 1: I added the code inside my function but still get a parse error at "xCoordinate + x" ...

like image 276
ManfredP Avatar asked Jun 28 '16 20:06

ManfredP


1 Answers

Given that this is your first time with Haskell, go with the record update answer already mentioned. However, for people googling this in the future, and for you too if you are feeling more ambitious (or for future learning), Haskell has this very popular and extremely powerful library called lens.

Here's how you can engineer a solution to your problem using it.

{-# LANGUAGE TemplateHaskell #-}
import Control.Lens

data Rectangle = Rectangle { _xCoordinate :: Int
                           , _yCoordinate :: Int
                           , _width :: Int
                           , _height :: Int
                           } deriving (Show)
makeLenses ''Rectangle

move :: Rectangle -> Int -> Int -> Rectangle
move rect dx dy= rect
                   & xCoordinate +~ dx
                   & yCoordinate +~ dy

This solution may not seem more powerful initially, but when you start trying to update nested records, I assure you the advantage becomes clear.

like image 82
Alec Avatar answered Nov 09 '22 14:11

Alec