Lostinfrance
Lostinfrance

Reputation: 13

Will this function be evaluated lazily?

I'm trying to understand if the following function will be evaluated lazily.

My understanding is "head" will take the first item from a list. Will optimalTests just evaluate the first item in [Test] or will all Tests in [Test] be created before head is subsequently called?

optimalTests :: State -> [Test]

--implementation here

getAnyTest :: State -> Test

getAnyTest s = head(optimalTests s)

Upvotes: 1

Views: 99

Answers (2)

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

I'd recommend messing about with the :print and :sprint commands in ghci to see lazy evaluation in action. For example:

Prelude> let names = ["Joe", "Jen", "Anne"]
Prelude> let hellos = map ((++) "Hello ") names
Prelude> head hellos
"Hello Joe"
Prelude> :sprint hellos
hellos = "Hello Joe" : _
Prelude> length hellos
3
Prelude> :sprint hellos
hellos = ["Hello Joe",_,_]
Prelude> last hellos
"Hello Anne"
Prelude> :sprint hellos
hellos = ["Hello Joe",_,"Hello Anne"]

That way you can see how the list is progressively evaluated as you call different functions on it. The _ represents an unevaluated thunk.

You could load your code into ghci and experiment in a similar way. Just make sure you assign things to variables or they will be evaluated by the REPL.

Upvotes: 3

jamshidh
jamshidh

Reputation: 12070

You are correct, it will only create the first value, nothing else...

You could test this by returning an array that crashes on the second element.

optimalTests _ = [aValidValue, error "crash!"]

If the program doesn't crash (it won't), that means it never tried to evaluate the second item.

Upvotes: 0

Related Questions