简体   繁体   中英

How can takeWhile terminate on infinite lists?

If I have takeWhile (<15) [1,3..] how can this terminate? How does Haskell know that there is not a 2 hiding at the end of the list?

A better example might be a sin function where we wound have infinitely many similar values under 15 that would repeat forever.

takeWhile (<15) doesn't take all the values less than 15—that's what filter does. Rather, takeWhile (<15) takes the longest prefix of the list that contains values all less than 15. As soon as it encounters an item 15 or above, that's the longest prefix, and it can stop.

That said, your example of a sin function indeed would not terminate, simply because all values are less than 15. In that case, takeWhile (<15) would produce an infinite list, identical to its input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM