Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read this List?

Tags:

list

haskell

My apologies if my question is not well worded but I seem to have a lack of words to specifically ask.

I found a line that results in a list of all multiples of three from 1 to 1000 while searching for Haskell learning rescources. I understand what this line does, it is not too difficult to see evaluated in GHCi.

[n | n <- [1..1000], n `rem` 3 == 0]

My actual problem is i do not know how to read this line in plain englisch and how exactly the list is generated and what n | n <- [1..1000] means. Can this be read similar to a for loop?

Such an expression was not covered in the basic tutorials I read. Where can I find documentation that is to be considered beginners read and covers how to plain read expressions?

It would greatly improve my learing process if I actually had some vocabulary describing what I type there ;)

like image 981
matthias krull Avatar asked Dec 03 '22 01:12

matthias krull


2 Answers

[n | n <- [1..1000], n `rem` 3 == 0] 

is called a list comprehension. It can basically be read as: "List of n, where n is in range 1 to 1000 and n remainder 3 == 0".

like image 99
Poindexter Avatar answered Dec 19 '22 16:12

Poindexter


[n | n <- [1..1000], nrem3 == 0] is the list of all n such that n is in [1 .. 1000] and n `rem` 3 == 0.

It's meant to read similarly to set notation (i.e. {n | n ∈ (1..1000), n ≡ 0 mod 3}).

like image 38
sepp2k Avatar answered Dec 19 '22 18:12

sepp2k