I'm learning Haskell for fun, following Learn you a Haskell. Range can go to infinity with numbers when using [1..]
. With characters, where does the range ['a'..]
stop ? I kinda suppose the last character of the Unicode table, but I really know nothing about Haskell so just asking !
(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.
The left arrow gets used in do notation as something similar to variable binding, in list comprehensions for the same (I'm assuming they are the same, as list comprehensions look like condensed do blocks), and in pattern guards, which have the form (p <- e). All of those constructs bind a new variable.
The expression in the parentheses is a lambda function. The backslash is used as the nearest ASCII equivalent to the Greek letter lambda (λ). This lambda function takes two arguments, x and str , and it evaluates to "x + read str".
in goes along with let to name one or more local expressions in a pure function.
If you want to know where the range stops, just get the last item…
ghci> last ['a'.. ] '\1114111'
Another method: Char
is a bounded type, i.e. a type with minimum and maximum values defined. Types in the Bounded
class provide a maxBound
value. Since maxBound
is polymorphic, you have to explicitly state the type of the value you're looking for.
ghci> maxBound :: Char '\1114111' ghci> maxBound :: Int 9223372036854775807
There is no maxBound
for Integer
since they are unbounded.
The Haskell prelude explains the connection between ['a'..]
and maxBound
. The notation ['a'..]
is syntactic sugar for enumFrom a
; here enumFrom
is a method of the Enum
type class. The documentation of Enum
specifies that when the type is also an instance of Bounded
, enumFrom x
should be equivalent to enumFromTo x maxBound
, or more readably, [x..] = [x..maxBound]
. So the last element of ['a'..]
must be the same as maxBound :: Char
.
last ['a'.. ]
does iterate over the list, but a modern computer can count to a million in an eyeblink. It's not something you would want to put in a tight loop, but as something you run just once it isn't a big burden. If you try it out in a less optimized implementation such as Hugs instead of GHC, you may need to wait for the result. In contrast last [0..]
would take approximately forever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With