Hacker News new | ask | show | jobs
by flebron 48 days ago
The website asks what they do in Haskell. The answer is property modification and reading, as well as very powerful traversal constructs, use lenses (https://hackage.haskell.org/package/lens , tutorial at https://hackage.haskell.org/package/lens-tutorial-1.0.5/docs...).
1 comments

What would be the equivalent to this in Haskell (with or without lens):

    cat = Cat(age=3)
    l = [1, [2, cat], 4]
    alt l[1][1].age.=9
That would give us l equal to:

    [1, [2, Cat(age=9)], 4]
In Haskell this list is not well-typed

    l = [1, [2, cat], 4]
There are a few different ways to cook this up. Here's one:

    {-# LANGUAGE TemplateHaskell #-}
    
    import Control.Lens
    
    data Cat = Cat { _age :: Int }
      deriving Show
    makeLenses ''Cat
    
    data Item
      = I Int
      | L [Item]
      | C Cat
      deriving Show
    
    makePrisms ''Item
    
    cat :: Cat
    cat = Cat 3
    
    l :: [Item]
    l = [I 1, L [I 2, C cat], I 4]
    
    l' :: [Item]
    l' = set (ix 1 . _L . ix 1 . _C . age) 9 l
    

    ghci> l'
    [I 1,L [I 2,C (Cat {_age = 9})],I 4]