Change the current list by adding an item - Haskell 101

I would like to add an item to the "movies" list of a type Directortype variable billy.

type Name  = String
type Movie = String
data Director = Director {name:: Name, movies::[Movie]}
    deriving (Show)
let billy = Director "Billy J." ["Good movie 1"]

--addMovieToDirector :: Movie -> Director -> Director
addMovieToDirector m (Director n ms) = Director n (m:ms)

The problem in the previous function does not update the billy movie list, it creates a new one Directorwith the desired list (the changes are not saved to the bill). How can I work with a bill list without creating another Director? I understand that Haskell works with constants, but then I have to create another “billy” variable every time I change the list?

Thank!

+4
source share
2 answers

What you would like to do can be described as “in-place modification” or “use of mutable data”.

Haskell . , " ", ​​ IO , unsafePerformIO.

, , , Haskell .

, . "" .

billy , .

, Haskell, - - .

, , , : " , "?

: : ( , ..) ( , ), ( ) - ( ), . , - .

, , - : c b, a, x, (c . b . a) x c (b (a x)) , , c $ b $ a x.

, , , , .

, , ( ). , , Haskell, .

, .:)

, .;)

+7

State, - . :

module Main where

import Control.Monad.State

type GameValue = Int
type GameState = (Bool, Int)

type Name  = String
type Movie = String
data Director = Director {name:: Name, movies::[Movie]}
    deriving (Show)

addMovieToDirector :: Movie -> Director -> Director
addMovieToDirector m (Director n ms) = Director n (m:ms)


handleDirector :: Name -> State Director Director
handleDirector m = do
    director <- get
    put (addMovieToDirector m director)
    returnDirector

returnDirector = do
    director <- get
    return director

startState = Director "Billy J." ["Good movie 1"]

main = print $ evalState (handleDirector "Good movie 2") startState

{name = "Billy J.", movies = [ " 2", " 1" ]}

handleDirector Name -> State Director Director Director "result", , Director. get , put , evalstate "" , State.

0

Source: https://habr.com/ru/post/1689005/


All Articles