Personal tools

99 questions/Solutions/22

From HaskellWiki

< 99 questions | Solutions(Difference between revisions)
Jump to: navigation, search
 
(slightly modified the version with guards so that it will make backwards ranges too)
Line 14: Line 14:
 
or
 
or
 
<haskell>
 
<haskell>
range i k
+
range start stop
     | i <= k = i : range (i + 1) k
+
     | start > stop  = reverse (range stop start)
     | i > k = []
+
     | start == stop = [stop]
 +
    | start < stop  = start:range (start+1) stop
 
</haskell>
 
</haskell>
  
 
Since there's already syntactic sugar for ranges, there's usually no reason to define a function like 'range' in Haskell. In fact, the syntactic sugar is implemented using the enumFromTo function, which is exactly what 'range' should be.
 
Since there's already syntactic sugar for ranges, there's usually no reason to define a function like 'range' in Haskell. In fact, the syntactic sugar is implemented using the enumFromTo function, which is exactly what 'range' should be.

Revision as of 05:22, 20 November 2010

Create a list containing all integers within a given range.

range x y = [x..y]

or

range = enumFromTo

or

range x y = take (y-x+1) $ iterate (+1) x

or

range start stop
    | start > stop  = reverse (range stop start)
    | start == stop = [stop]
    | start < stop  = start:range (start+1) stop

Since there's already syntactic sugar for ranges, there's usually no reason to define a function like 'range' in Haskell. In fact, the syntactic sugar is implemented using the enumFromTo function, which is exactly what 'range' should be.