Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding `evaluate` Functiion

The Haskell docs explain the evaluate function:

Forces its argument to be evaluated to weak head normal form when the resultant IO action is executed.

Prelude Control.Exception> let xs = [1..100] :: [Int]                                                                   Prelude Control.Exception> :sprint xs
xs = _
Prelude Control.Exception> let ys = evaluate xs
Prelude Control.Exception> :t ys
ys :: IO [Int]
Prelude Control.Exception> ys
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,6Prelu2,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
Prelude Control.Exception> :sprint xs
xs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,
      24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,
      46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,
      68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,
      90,91,92,93,94,95,96,97,98,99,100]
Prelude Control.Exception> :sprint ys
ys = _

Why is ys not in Weak Head Normal Form, i.e. :sprint ys does not equal _ : _?

like image 789
Kevin Meredith Avatar asked May 19 '26 09:05

Kevin Meredith


2 Answers

Your ys value has a type of IO [Int]. Now, IO is a abstract type and can be thought of as RealWorld -> ([Int], RealWorld) in your case. Now this IO value is already in weak head normal form. That's why you see it as _ when you do sprint on it.

Why is ys not in Weak Head Normal Form, i.e. :sprint ys does not equal _ : _?

ys outer term cannot be _ : _ because it's not a list but it is value of type IO [Int].

like image 79
Sibi Avatar answered May 20 '26 22:05

Sibi


In addition to what has been said by Sibi, here is a way to see that evaluate actually does what the docs say:

GHCi> let xs = [1..100] :: [Int]
GHCi> :sprint xs
xs = _
GHCi> let a = evaluate xs >> return ()
GHCi> a
GHCi> :sprint xs
xs = 1 : _
like image 41
kosmikus Avatar answered May 20 '26 22:05

kosmikus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!