hask1023
hask1023

Reputation: 109

Do loops in Haskell

In Haskell when you use <- in a do loop on a list, does it return the whole list?

so:

        do
      //some code
         c <-[1..4]
        //some code

Would c be [1,2,3,4]?

Upvotes: 1

Views: 154

Answers (1)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

Why ask us when you can ask an interpreter?

$ ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
Loaded package environment from /home/tommd/.ghc/x86_64-linux-8.10.7/environments/default
iPrelude> import Debug.Trace
Prelude Debug.Trace> :{
Prelude Debug.Trace| do
Prelude Debug.Trace| c <- [1..4]
Prelude Debug.Trace| trace ("C is currently: " ++ show c) (return c)
Prelude Debug.Trace| :}
C is currently: 1
[1C is currently: 2
,2C is currently: 3
,3C is currently: 4
,4]

notice the output is interleaved with the trace messages, so you can see c takes the values of 1 through 4 one at a time in the list monad.

If that last part "in the list monad" wasn't immediately obvious then do not ignore it - that is a critical part in understanding this answer and how it can (and can not) be applied to your use of the Haskell language.

Upvotes: 3

Related Questions