Saturday 30 April 2016

Haskell: lists: Define range of elements


Suppose you want to create a list of first 100 numbers, don't you think how tedious it is to type all the elements? By using .. (range) operator you can solve this problem.

[1..100] return all the elements from 1 to 100.
Prelude> [1..100]
[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]


By using ranges you can specify a step. For example [2, 4, .. 50] return all the even numbers from 2 to 50. Here step is difference between second and first element, 4-2 = 2.
Prelude> [2, 4 .. 50]
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50]
Prelude> 
Prelude> [1, 3 .. 50]
[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49]
Prelude> 
Prelude> [6, 12  .. 50]
[6,12,18,24,30,36,42,48]
Prelude> 
Prelude> [50, 48 .. -50]
[50,48,46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6,4,2,0,-2,-4,-6,-8,-10,-12,-14,-16,-18,-20,-22,-24,-26,-28,-30,-32,-34,-36,-38,-40,-42,-44,-46,-48,-50]
Prelude>
Prelude> [49, 47 .. -50]
[49,47,45,43,41,39,37,35,33,31,29,27,25,23,21,19,17,15,13,11,9,7,5,3,1,-1,-3,-5,-7,-9,-11,-13,-15,-17,-19,-21,-23,-25,-27,-29,-31,-33,-35,-37,-39,-41,-43,-45,-47,-49]


Ranges are applicable to characters also.
Prelude> ['a'..'z']
"abcdefghijklmnopqrstuvwxyz"
Prelude> 
Prelude> ['A'..'Z']
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Prelude> 
Prelude> ['A', 'C'..'Z']
"ACEGIKMOQSUWY"
Prelude> ['A', 'F'..'Z']
"AFKPUZ"


Since floating-point numbers are not precise, don't expect range to produce all values exactly.
Prelude> [10.9, 10.8..10.0]
[10.9,10.8,10.700000000000001,10.600000000000001,10.500000000000002,10.400000000000002,10.300000000000002,10.200000000000003,10.100000000000003,10.000000000000004]


Infinite lists
Haskell support infinite lists, For example, [1..] generates infinite list like [1, 2, 3, ……..], Since Haskell performs lazy evaluation, Haskell won’t evaluate until it required.
Prelude> head [1..]
1
Prelude> take 50 [1..]
[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]




Previous                                                 Next                                                 Home

No comments:

Post a Comment