Hacker News new | ask | show | jobs
by leontrolski 55 days ago
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]
1 comments

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]