How can a time function exist in functional programming?

后端 未结 15 514
Happy的楠姐
Happy的楠姐 2020-12-04 04:26

I\'ve to admit that I don\'t know much about functional programming. I read about it from here and there, and so came to know that in functional programming, a function retu

15条回答
  •  悲哀的现实
    2020-12-04 04:59

    Your question conflates two related measures of a computer language: functional/imperative and pure/impure.

    A functional language defines relationships between inputs and outputs of functions, and an imperative language describes specific operations in a specific order to perform.

    A pure language does not create or depend on side effects, and an impure language uses them throughout.

    One-hundred percent pure programs are basically useless. They may perform an interesting calculation, but because they cannot have side effects they have no input or output so you would never know what they calculated.

    To be useful at all, a program has to be at least a smidge impure. One way to make a pure program useful is to put it inside a thin impure wrapper. Like this untested Haskell program:

    -- this is a pure function, written in functional style.
    fib 0 = 0
    fib 1 = 1
    fib n = fib (n-1) + fib (n-2)
    
    -- This is an impure wrapper around the pure function, written in imperative style
    -- It depends on inputs and produces outputs.
    main = do
        putStrLn "Please enter the input parameter"
        inputStr <- readLine
        putStrLn "Starting time:"
        getCurrentTime >>= print
        let inputInt = read inputStr    -- this line is pure
        let result = fib inputInt       -- this is also pure
        putStrLn "Result:"
        print result
        putStrLn "Ending time:"
        getCurrentTime >>= print
    

提交回复
热议问题