A good way to create loops

Haskell has no loops, like many other languages. I understand the reasons for this and some of the different approaches used to solve problems without them. However, when a loop structure is needed, I am not sure if I am creating the right / good loop correctly.

For example (trivial function):

dumdum = do
         putStrLn "Enter something"
         num <- getLine
         putStrLn $ "You entered: " ++ num
         dumdum

This works great, but is there a potential problem in the code?

Another example:

a = do 
    putStrLn "1"
    putStrLn "2"
    a

If implemented in an imperative language like Python, it will look like this:

def a():
     print ("1")
     print ("2")
     a()

This ultimately leads to a maximum recursion depth error. This doesn't seem to be the case in Haskell, but I'm not sure if this could cause potential problems.

, , Control.Monad.LoopWhile Control.Monad.forever - ? ( Haskell .)

+4
2

- , , . , goto 1. , , n , 2:

sum :: Int -> Int
sum n = sum' 0 n

sum' !s 0 = s
sum' !s n = sum' (s+n) (n-1)

:

function sum(N)

    var s, n = 0, N
    loop: 
       if n == 0 then
           return s
       else
           s,n = (s+n, n-1)
           goto loop

, Haskell . .

gotos. , ( gotos, ) , , , , . , (, while ..) , Haskell . , , map foldl' 3 , Control.Monad monad-loops, . , , .


1 , "Lambda the ultimate GOTO" , , , . , Haskell , , - O (1) ( " " )

2 , , ( Haskell ). "!", , .

3 foldl' foldl - .

+9

, , Control.Monad.LoopWhile Control.Monad.forever - ? ( Haskell .)

, . , "" Haskell (.. ) . , , , , forever, .

, , Haskell , . , . , - . , Python, " for", , -. Haskell

  • map, fold, any, all, scan, mapAccum, unfold, find, filter (Data.List)
  • mapM, forM, forever (Control.Monad)
  • traverse, for (Data.Traversable)
  • foldMap, asum, concatMap (Data.Foldable)

, !

( ) .

Haskell , . , - for Python, , , . , - map Haskell, , , , , " Functor", , , map !


, askNum "( , IO... , ), - , . , , " " forever, forever !

:

askNum = do
         putStrLn "Enter something"
         num <- getLine
         putStrLn "You entered: " ++ num

dumdum = forever askNum

, , askNum "

dumdum = forever $ do
           putStrLn "Enter something"
           num <- getLine
           putStrLn "You entered: " ++ num
+6

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


All Articles