r/shittyprogramming • u/Alekzcb • Jul 11 '19
Generating Intervals in Haskell
I find myself often wanting lists of consecutive numbers like [3,4,5,6,7] but it's very difficult to make these in haskal since it doesn't have any for-loops. But I've come up with a simple function you can stick in you code that will do this for you -- no more hassle :)
interval :: Num a => Int -> Int -> [a]
interval = ((fromIntegral.length<$>).).flip(.)((iterate(([]:).(<$>)(():))(fail$undefined)!!).succ).drop
interval 3 7 ~> [3,4,5,6,7]
33
Upvotes
View all comments
Show parent comment
12
u/Alekzcb Jul 11 '19
Basic prerequisite Haskell knowledge:
There is a type called "unit", written as an empty vector:
(). It doesn't really do anything.Lists are defined as either
[](empty list) orx:xs(some itemxat the start of a listxs).Explanation:
The core of the
intervalfunction is the partFor unimportant reasons, we can rewrite this as:
iterate f xrepeats the functionfonxand puts each iteration in a list, thus generating[x, f x, f (f x), f (f (f x)), ...]. The function we pass toiterateis(([]:) . map (():))which basically takes a list of lists of units (let's say collection of lists for simplicity), adds an extra unit to each list, then puts an empty list into the collection.We start with an empty list, so the iteration goes
Notice the length of the
nth list isn, but also thenth list contains lists of every length between0andn.The function
intervaltakes twoIntarguments: let's call themaandb. It grabs the(b+1)th list thatiteratemakes, which is going to be[[], [()], [(), ()], [(), (), ()], ..., z], the last elementzbeing a list containing exactlybunits.Now we convert each list of units to a
Intbylength, so we have the list[0, 1, ..., b]. Then drop the firstavalues, leaving us with the interval we want.Then I garbled the syntax around.