Функциональный цикл while относится к циклу while, реализованному с использованием принципов функционального программирования. В функциональном программировании упор делается на неизменяемость и отсутствие изменяемого состояния. Вот несколько способов реализации функционального цикла while на разных языках программирования:
-
Python:
def functional_while_loop(condition, body): if condition(): body() functional_while_loop(condition, body) # Usage: count = 0 def condition(): return count < 5 def body(): global count print(count) count += 1 functional_while_loop(condition, body) -
JavaScript:
function functionalWhileLoop(condition, body) { if (condition()) { body(); functionalWhileLoop(condition, body); } } // Usage: let count = 0; function condition() { return count < 5; } function body() { console.log(count); count++; } functionalWhileLoop(condition, body); -
Рубин:
def functional_while_loop(condition, body) if condition.call body.call functional_while_loop(condition, body) end end # Usage: count = 0 condition = -> { count < 5 } body = -> { puts count; count += 1 } functional_while_loop(condition, body) -
Haskell:
functionalWhileLoop :: (a -> Bool) -> (a -> a) -> a -> IO () functionalWhileLoop condition body state = do if condition state then do body state functionalWhileLoop condition body (body state) else return () -- Usage: count = 0 condition x = x < 5 body x = putStrLn (show x) main = functionalWhileLoop condition body count