Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map vs Filter over infinite lists?

Tags:

haskell

I'm learning Haskell and i've run into something i can't understand and i can't find an explanation. So, I was testing some functions over infinite lists to see how they worked, and i found a diference between map and filter that I'd like to understand.

Prelude.map definition:

map _ []     = []
map f (x:xs) = f x : map f xs

Prelude.filter definition:

filter _pred []    = []
filter pred (x:xs)
  | pred x         = x : filter pred xs
  | otherwise      = filter pred xs

If I run this:

map (==5) [1..]

The output starts and it never ends, until i stop it. Wich makes sense since the list is infinite.

But now if i run this:

filter (==5) [1..]

I see nothing, not even [5,. Which also makes sense since the list is infinite too, but i want to understand what's the difference beetwen map and filter that makes this. Thank you and sorry for my english!

Edit: I was using tryhaskell.org and that was the problem!

like image 859
DemianArdus Avatar asked May 11 '14 22:05

DemianArdus


People also ask

How to use filter and map function simultaneously to an array?

Given an array and the task is to use filter and map function simultaneously to the given array. First lets look at map and filter functions in brief: filter () method: This method returns a new array containing the elements that passes a certain test performed on an original array.

What is the difference between map and filter in JavaScript?

Like filter, map also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array. And last but not least …

Why can't I use map() and filter() in Python?

The trouble with functions like map () and filter () is in the limited nature of their input parameters verses a list comprehension. With map () and filter () you are locked into being required to ONLY use iterables as the additional arguments after your method pointer.

Why are map() and filter() so hard to use?

Everybody’s favorite answer, I know! The comparison comes down to the flexibility of your code, or at least how flexible you want your code to be. The trouble with functions like map () and filter () is in the limited nature of their input parameters verses a list comprehension.


1 Answers

As discovered in the comments, this is due to using Try Haskell. From experimentation, it appears that it will wait for the program to terminate, 3 seconds to elapse, or 1024 characters of output to be produced, before ending and sending you the result. Unfortunately, filter (==5) [1..] will only produce a measly two characters ([5), not meeting the 1024 character limit, and for some reason or another Try Haskell won't send [5 back to you. Running it in a real GHCi should work just fine.

like image 73
icktoofay Avatar answered Oct 12 '22 18:10

icktoofay