Nested functions: misuse of side effects?

I study functional programming and try to solve a couple of problems in a functional style. One thing that I experienced dividing my task into functions seemed to have two options: to use several disparate functions with similar parameter lists or to use nested functions that could simply refer to bindings in the parent function as closures.

Although I switched to the second approach because it made function calls smaller and seemed to “feel” better, from my reading it seems that I might miss one of the main points of functional programming, as it seems to be “side” ? Now the provided these nested functions cannot change external bindings, because the language I used prevents this, but if you look at each individual internal function, you cannot say "with the same parameters, this function will return the same results", because they use variables from the parent scope ... Am I right?

What is the desired way?

Thanks!

+5
source share
3

- . ""; , .

, , . , . :

let factorial n =
    let rec facHelper p n =
        if n = 1 then p else facHelper (p*n) (n-1)
    in
    facHelper 1 n

​​, facHelper , p.

, , .

+2

- . , . , , , .

:

(define (foo a)
  (define (bar b)
    (+ a b))      ; getting a from outer scope, not purely functional
  (bar 3))

(define (foo a)
  (define (bar a b)
    (+ a b))      ; getting a from function parameters, purely functional
  (bar a 3))


(define (bar a b) ; since this is purely functional, we can remove it from its
  (+ a b))        ; environment and it still works

(define (foo a)
  (bar a 3))

, .

+3

() Haskell:

putLines :: [String] -> IO ()
putLines lines = putStr string
    where string = concat lines

string - . , , lines , , ? ( Haskell !) "" ?

+1

All Articles