O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Introduction

If you have worked with object-oriented programming, then you must be aware of the properties (such as in C# or Python, or even in managed C++). Usually, we can access the properties inside an object and also set the property to some value:

    Point point = Point(1.0, 2.0);
    double x = point.x; // Should be 1.0
    point.x = 3.0;      // Now point x is changed to 3.0

Though the preceding code mutates the data, it is very convenient to get and set a property. Imagine doing the same with Haskell:

    data Point = Point Double Double

    x :: Point -> Double
    x (Point xv _) = xv

    setx :: Point -> Double -> Point
    setx (Point _ y) x = Point x y

We need to de-construct a type, and reconstruct it again. If we had some generic way of accessing a field inside ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required