Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Haskell, where does the range ['a'..] stop?

Tags:

haskell

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 !

like image 837
DjebbZ Avatar asked Sep 09 '13 12:09

DjebbZ


People also ask

What does -> mean in Haskell?

(->) 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.

What does left arrow mean in Haskell?

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.

What does backslash mean in Haskell?

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".

What does in do in Haskell?

in goes along with let to name one or more local expressions in a pure function.


1 Answers

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.

like image 80
w.b Avatar answered Sep 22 '22 09:09

w.b