how to increment a variable in functional programming

后端 未结 4 1728
逝去的感伤
逝去的感伤 2020-11-29 07:45

How do you increment a variable in a functional programming language?

For example, I want to do:

main :: IO ()
main = do
    let i = 0
    i = i + 1
         


        
4条回答
  •  半阙折子戏
    2020-11-29 08:15

    There are several solutions to translate imperative i=i+1 programming to functional programming. Recursive function solution is the recommended way in functional programming, creating a state is almost never what you want to do.

    After a while you will learn that you can use [1..] if you need a index for example, but it takes a lot of time and practice to think functionally instead of imperatively.

    Here's a other way to do something similar as i=i+1 not identical because there aren't any destructive updates. Note that the State monad example is just for illustration, you probably want [1..] instead:

    module Count where
    import Control.Monad.State
    
    count :: Int -> Int
    count c = c+1
    
    count' :: State Int Int
    count' = do
        c <- get
        put (c+1)
        return (c+1)
    
    main :: IO ()
    main = do
                -- purely functional, value-modifying (state-passing) way:
        print $ count . count . count . count . count . count $ 0
                -- purely functional, State Monad way
        print $ (`evalState` 0) $ do { 
                count' ; count' ; count' ; count' ; count' ; count' } 
    

提交回复
热议问题