2

How do I increment a attribute? I created a type User

data user = User{
username :: String,
passwort :: String,
points :: Int
}

user = user {username ="Test",
             passwort="test123",
             points=100
             }

I want to increment the points by 10, I tryed to do something similar to this like in other programming lenguages points += 10

userplus10 = user{points = points +10}

(btw. this doesnt work) creating a new user but with another value at points.

Kevin
  • 145
  • 7

1 Answers1

7

It does work, but you need to specify whose points you want to increment. users, right?

userplus10 = user{points = points user + 10}

A better way of doing this kind of stuff are lenses though.

{-# LANGUAGE TemplateHaskell, Rank2Types #-}

import Control.Lens

data User = User
   { _username :: String,
   , _passwort :: String,
   , _points :: Int
   }
makeLenses ''User

user = user {username ="Test", passwort="test123", points=100}

userPlus10 = user & points +~ 10
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
  • Sorry i'm new at Haskell, do both things the same? and is one way better than other? – Kevin Oct 12 '19 at 22:21
  • I'd argue that the lens version is indeed better, however it requires a heavyweight library and some pretty advanced polymorphism trickery (hence the `-XRank2Types` extension). – leftaroundabout Oct 12 '19 at 22:41
  • 2
    [This](http://www.haskellforall.com/2013/05/program-imperatively-using-haskell.html) is a great article, suitable for those relatively new to Haskell, about how lenses enable you to write "OO-looking" code in Haskell. Also, while the whole of the Lens package is indeed a beast, there are various "simplified" Lens packages out there which give you all the most commonly-used features without needing tons of dependencies, eg. [this one](http://hackage.haskell.org/package/lens-simple) – Robin Zigmond Oct 12 '19 at 22:54