Why doesnt map sqrt[1..] not give an infinite recursion???? How can i better understand the haskell?

```
sqrtSums :: Int
sqrtSums = length ( takeWhile (<1000) (scanl1 (+) (map sqrt[1..]))) + 1
```

Haskell evaluates expressions *lazily*. This means that evaluation only occurs when it is demanded. In this example `takeWhile (< 1000)`

repeatedly demands answers from `scanl1 (+) (map sqrt [1..])`

but *stops* after one of them exceeds `1000`

. The moment this starts happening Haskell ceases to evaluate more of the (truly infinite) list.

We can see this in the small by cutting away some pieces from this example

```
>>> takeWhile (< 10) [1..]
[1,2,3,4,5,6,7,8,9]
```

Here we have an expression that represents an infinite list (`[1..]`

) but `takeWhile`

is ensuring that the total expression only demands *some* of those countless values. Without the `takeWhile`

Haskell will try to print the entire infinite list

```
>>> [1..]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24Interrupted.
```

But again we notice that Haskell demands each element one-by-one only as it needs them in order to print. In a strict language we'd run out of ram trying to represent the infinite list internally prior to printing the very first answer.

Lists in Haskell behave as if they have a built-in iterator or stream interface, because the entire language uses lazy evaluation by default, which means only calculating results when they're needed by the calling function.

In your example,

```
sqrtSums = length ( takeWhile (<1000) (scanl1 (+) (map sqrt[1..]))) + 1
```

it's as if `length`

keeps asking `takeWhile`

for another element,

which asks `scanl1`

for another element,

which asks `map`

for another element,

which asks `[1..]`

for another element.

Once `takeWhile`

gets something that's not `<1000`

, it doesn't ask `scanl1`

for any more elements, so `[1..]`

never gets fully evaluated.

An unevaluated expression is called a *thunk*, and getting answers out of thunks is called *reducing* them. For example, the thunk `[1..]`

first gets reduced to `1:[2..]`

. In a lot of programming languages, by writing the expression, you force the compiler/runtime to calculate it, but not in Haskell. I could write `ignore x = 3`

and do `ignore (1/0)`

- I'd get 3 without causing an error, because `1/0`

doesn't need to be calculated to produce the `3`

- it just doesn't appear in the right hand side that I'm trying to produce.

Similarly, you don't need to produce any elements in your list beyond 131 because by then the sum has exceeded 1000, and `takeWhile`

produces an empty list `[]`

, at which point `length`

returns `130`

and `sqrtSums`

produces `131`

.

Similar Questions

In my play/swagger/reactivemongo application i use the following function in the controller to get a list of results with EntityID 8. @ApiOperation(value = Gets the item of a specific ID, notes =

The original question Recent version(s) of Haskell (> 7.4.2?) come with an mtl package that no longer provides a State constructor per se, instead providing a state function. This messes up the exa

Why does Haskell allow to do a list of Shape as in the first exemple, but not as in the second example? As far as I know, both lists would have elements that are either { name :: String, position :: V

Possible Duplicate: Why is such a function definition not allowed in haskell? I'm a newcomer to the world of Haskell, migrating over from Lisp. I'm trying to adjust to Haskell's fundamentally differ

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself

The problem I am trying to solve using Haskell is defined as this: Write a function that takes a list of numbers in increasing order and returns a list of all Integers (in increasing order) that can b

Suppose that the Haskell or lambda calculus presents the following function types: A -> B -> C (A -> B) -> C How are these two different?

Ive been trying this question for hours, still stuck on it. Can anyone help. Looking for suggestions: Use a list comprehension to define a function triples n which returns a list of positive integer t

Another poster asked about preferred syntax for infinite loops. A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this: for (;;) { int scoped_variable

Why is the Haskell implementation so focused on linked lists? For example, I know Data.Sequence is more efficient with most of the list operations (except for the cons operation), and is used a lot; s

Hi Im new to Haskell and wish to write a simple code. I want to write a function which creates a list of numbers. Where it starts of with 1 and increase with 2n+1 and 3n+1 so for example output should

For cultural and intellectual enrichment, I've decided to learn a bit of Haskell. I've been reading Hughes' Why Functional Programming Matters and am trying to translate its code into true Haskell.

I want to include more than 1 case statement in a haskell function (see below for example of hypothetical function). However, it is not legal haskell. What is a better way of accomplishing the same th

Given a finite list of elements, how can I create a (lazily-evaluated, thanks LINQ!) infinite list that just keeps iterating over my initial list? If the initial list is {1, 2, 3}, I want the new list

For those with suspicious minds, this is not homework, just curious. Given a finite alphabet, is it possible to construct a list of infinitely long words made from the alphabet in reverse lexographic

I can see why it chooses to stop after it's found a given number of errors. But why stop at 102? Why not 99, 100 or 128?

Here's the SQLite3 Haskell bindings with the ability to create function: http://hackage.haskell.org/packages/archive/sqlite/0.5.1/doc/html/Database-SQLite.html But I can't get to use this feature, I w

I don't understand why this while loop is infinite: window.prevRandomNumber = -1; function getRandomNumber(limit) { if (!limit) limit = 9; var actualRandomNumber = Math.floor((Math.random() * limit) +

I want to show an alert message if user click on second tan without submitting the form on the first tab, the problem I face of infinite alert messages that's show when user click on tab, here is the

I'm currently trying to learn Haskell, but I'm struggling with understanding the syntax. For example, take the map function: map :: (s -> t) -> [s] -> [t] map f [] = [] map f (x:xs) = f x : m

How can I stop the spin? Something strange happens. Here is the code that doesn't work: <body> <div id=spin> </div> <button type=submit onclick=spin_stop(); id=stop>St

For the first time I've encountered an infinite loop in a Haskell program I'm writing. I've narrowed it down to a quite specific section of code, but I cannot seem to pinpoint exactly where I have a n

This question already has an answer here: Finite comprehension of an infinite list 4 answers Forgive my stupid question, I'm new to Haskell. I tried in Haskell the following: sum [fib n| n <

Can I stop the execution of an infinite loop in Scala REPL? Type this and try to stop it without quitting the REPL. while(true){} I thought something like Ctrl-C would work.

I am new to Haskell and I have the following problem. I have to create a list of numbers [f1, f2, f3...] where fi x = x ^ i. Then I have to create a function that applies the fi to a list of numbers.

This question is essentially a duplicate of Debugging infinite loops in Haskell programs with GHCi. The author there solved it manually, though I'd like to know other solutions. (my particular problem

I'm trying to create a function that returns itself in a tuple of values. Basically the idea is that the caller would get back transformed values, along with a new (curried) version of the function to

Currently working with Haskell on a function that takes a String in parameters and return a list of (Char, Int) The function occur works with multiple type and is used in the function called word. oc

I am attempting to write a function so that it can find the first two elements of a list, add them, and then place them at the head of the list. However I am running into unexpected errors when I try

I am working on a function in Haskell that will take one list and divide it into two evenly sized lists. Here is what I have: split (x:y:xs) = split2 ([((length(x:y:xs) `div` 2)-2) : x ++ y] : [xs]) s

I'm learning the basics of Haskell, and come across many tutorials saying that if a list is constructed from left to right using ++ is more efficient than from right to left. But I can't seem to under

Learning Haskell, I came across the fact that foldl creates thunks and might crash the stack, so it's better to use foldl' from Data.List. Why is it just foldl, and not, for example, foldr? Thanks

I make my next homework =) My task is to create infinite list with fibonacci numbers [0,1,1,2,3,5,8..] I can use any function from Prelude. My try: fibs2 :: [Integer] fibs2 = reverse $ foldr f [1,0] [

From haskell.org: quicksort :: Ord a => [a] -> [a] quicksort [] = [] quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) where lesser = filter (< p) xs greater = filter (>=

I am pretty new to Haskell. so this might be a bit silly. What I want is to do something like: map (\x -> x + **position in list**) [0, 0, 0] => [1, 2, 3] How can this be done?

I am an absolute newbie in Haskell yet trying to understand how it works. I want to write my own lazy list of integers such as [1,2,3,4,5...]. For list of ones I have written ones = 1 : ones and when

I'm new to haskell. I wrote a simple code. But it does not work. I'm getting this 'can not construct infinite type' error. How does it fix. reverse' list | null list = [] | otherwise = (reverse' (tail

I have a function for finite lists > kart :: [a] -> [b] -> [(a,b)] > kart xs ys = [(x,y) | x <- xs, y <- ys] but how to implement it for infinite lists? I have heard something about

I'm really an absolute newbie at Haskell, so I'm at a total loss as to how to debug some functions I wrote. When I call shuntingYard [3+4] I get back [], whereas I want to get back [34+]. Any and al

I´ve written a function in Haskell that takes three points in the plane, and checks if they´re on a straight line, or make a right or left turn. Here´s the code: detDirection :: Point -> Point ->

does anyone have an simple example of haskell-mpi scatterSend and scatterRecv. I've looked at the example included in the package, but couldn't get a good enough understanding based on just that one e

I'm completely new to coding and have started learning JavaScript recently. I don't understand why the following code causes an infinite loop. Why does the birthday(myAge) function not work within the

I came across an exercise in one of my lectures that left me confused on the output of [2, 2 .. 2]. Why when entering [2, 2 .. 2] it generates an infinite list with 2's. The way i understood the no

say I have a list in haskell [2,4,6,8,9,4] , and I want to start on the first element and then jump by one or two elements and get all possible combinations.so I should get a list of lists. so for the

I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop?

I am playing a sound infinite time using following code SoundPool sounds = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); beepSound = sounds.load(this, R.raw.beep, 1); beepSoundStream = sounds.play

I have a function in Haskell which finds the maximum value of an exponentiation from a list: prob99 = maximum $ map (\xs -> (head xs)^(head (tail xs))) numbers What I need to find is the location

Why infinite recursion leads to seg fault ? Why stack overflow leads to seg fault. I am looking for detailed explanation. int f() { f(); } int main() { f(); }

I need to run application in every X seconds, so, as far as cron does not work with seconds this way, I wrote a bash script with infinite loop having X seconds sleep in it. When I have to stop the run

I've started learning Haskell in the last couple of days and I'm having trouble with this piece of code. I'm trying to make a function that will generate a list of primes given an initial list (contai