Generate lower case ASCII alphabet

From Rosetta Code
Task
Generate lower case ASCII alphabet
You are encouraged to solve this task according to the task description, using any language you may know.

Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from 'a' to 'z'.

If the standard library contains such sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available.

It's bug prone to enumerate all the lowercase chars manually in the code. During code review it's not immediate to spot the bug in a Tcl line like this contained in a page of code:

<lang tcl>set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}</lang>

ABAP

<lang ABAP>DATA(alpha) = to_lower( sy-abcde ).</lang>

Ada

We start with a strong type definition: A character range that can only hold lower-case letters:

<lang Ada> type Lower_Case is new Character range 'a' .. 'z';</lang>

Now we define an array type and initialize the Array A of that type with the 26 letters: <lang Ada> type Arr_Type is array (Integer range <>) of Lower_Case;

  A : Arr_Type (1 .. 26) := "abcdefghijklmnopqrstuvwxyz";</lang>

Strong typing would catch two errors: (1) any upper-case letters or other symbols in the string assigned to A, and (2) too many or too few letters assigned to A. However, a letter might still appear twice (or more) in A, at the cost of one or more other letters. Array B is safe even against such errors:

<lang Ada> B : Arr_Type (1 .. 26); begin

  B(B'First) := 'a';
  for I in B'First .. B'Last-1 loop
     B(I+1) := Lower_Case'Succ(B(I));
  end loop; -- now all the B(I) are different</lang>

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.6.win32

<lang algol68> # in ALGOL 68, a STRING is an array of characters with flexible bounds #

   # so we can declare an array of 26 characters and assign a string      #
   # containing the lower-case letters to it                              #
   [ 26 ]CHAR lc := "abcdefghijklmnopqrstuvwxyz"

</lang> Alternative version <lang algol68> # fills lc with the 26 lower-case letters, assuming that #

   # they are consecutive in the character set, as they are in ASCII      #
   [ 26 ]CHAR lc;
   FOR i FROM LWB lc TO UPB lc
   DO
       lc[ i ] := REPR ( ABS "a" + ( i - 1 ) )
   OD</lang>

Applesoft BASIC

<lang ApplesoftBasic>L$="abcdefghijklmnopqrstuvwxyz"</lang> On the older model Apple II and Apple II plus, it is difficult to enter lower case characters. The following code generates the same string: <lang ApplesoftBasic>L$="":FORI=1TO26:L$=L$+CHR$(96+I):NEXT</lang>

ATS

<lang ATS> (* ****** ****** *) // // How to compile: // // patscc -DATS_MEMALLOC_LIBC -o lowercase lowercase.dats // (* ****** ****** *) //

  1. include

"share/atspre_staload.hats" // (* ****** ****** *)

implement main0 () = { // val N = 26 // val A = arrayref_tabulate_cloref<char> (

 i2sz(N), lam(i) => int2char0(char2int0('a') + sz2i(i))

) (* end of [val] *) // } (* end of [main0] *) </lang>

AutoHotkey

Works with: AutoHotkey 1.1

<lang AutoHotkey>a :={} Loop, 26 a.Insert(Chr(A_Index + 96))</lang>

AutoIt

<lang AutoIt> Func _a2z() Local $a2z = "" For $i = 97 To 122 $a2z &= Chr($i) Next Return $a2z EndFunc </lang>

AWK

Works with: gawk

Generate all character codes, and test each one if it matches the POSIX character class for "lowercase".

Note this is dependent on the locale-setting, and options, e.g. --traditional and --posix <lang AWK>

  1. syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWK

BEGIN {

   for (i=0; i<=255; i++) {
     c = sprintf("%c",i)
     if (c ~ /lower:/) {
       lower_chars = lower_chars c
     }
   }
   printf("%s %d: %s\n",ARGV[0],length(lower_chars),lower_chars)
   exit(0)

} </lang>

Output:
gawk_3_1_8 26: abcdefghijklmnopqrstuvwxyz
gawk_4_1_0 65: abcdefghijklmnopqrstuvwxyzƒsozªµºßàáâaäåæçèéêëìíîïdñòóôoöoùúûüy_ÿ

BBC BASIC

<lang bbcbasic> DIM lower&(25)

     FOR i%=0TO25
       lower&(i%)=ASC"a"+i%
     NEXT
     END</lang>

Befunge

The left hand side pushes the sequence 'a' to 'z' onto the stack in reverse order with a null terminator (a fairly typical Befunge pattern). The right hand side is just printing it out again to test. <lang Befunge>0"z":>"a"`#v_ >:#,_$@

    ^:- 1:<</lang>

Bracmat

<lang bracmat> a:?seq:?c & whl

 ' ( chr$(asc$!c+1):~>z:?c
   & !seq !c:?seq
   )

& !seq</lang>

C

<lang c>#include <stdlib.h>

  1. define N 26

int main() {

   unsigned char lower[N];
   for (size_t i = 0; i < N; i++) {
       lower[i] = i + 'a';
   }
   return EXIT_SUCCESS;

} </lang>

C++

C++ can do the task in the identical way as C, or else, it can use a STL function.

Works with: C++11

<lang cpp>#include <string>

  1. include <numeric>

int main() {

   std::string lower(26,' ');
   std::iota(lower.begin(), lower.end(), 'a');

}</lang>

C#

<lang csharp>namespace RosettaCode.GenerateLowerCaseASCIIAlphabet {

   using System;
   using System.Collections.Generic;
   internal class Program
   {
       private static IEnumerable<char> Alphabet
       {
           get
           {
               for (var character = 'a'; character <= 'z'; character++)
               {
                   yield return character;
               }
           }
       }
       private static void Main()
       {
           Console.WriteLine(string.Join(string.Empty, Alphabet));
       }
   }

}</lang>

Output:
abcdefghijklmnopqrstuvwxyz

Clojure

<lang clojure>(map char (range (int \a) (inc (int \z))))</lang>

Output:
(\a \b \c \d \e \f \g \h \i \j \k \l \m \n \o \p \q \r \s \t \u \v \w \x \y \z)

CoffeeScript

<lang coffeescript> (String.fromCharCode(x) for x in [97..122]) </lang>

Common Lisp

<lang lisp>(defvar *lower*

 (loop with a = (char-code #\a)
       for i upto 25
       collect (code-char (+ a i))))</lang>

D

The lower case ASCII letters of the Phobos standard library: <lang d>import std.ascii: lowercase;

void main() {}</lang>

The generation of the ASCII alphabet array: <lang d>void main() {

   char['z' - 'a' + 1] arr;
   foreach (immutable i, ref c; arr)
       c = 'a' + i;

}</lang>

An alternative version: <lang d>void main() {

   import std.range, std.algorithm, std.array;
   char[26] arr = 26.iota.map!(i => cast(char)('a' + i)).array;

}</lang> Another version: <lang d>void main() {

   char[] arr;
   foreach (immutable char c; 'a' .. 'z' + 1)
       arr ~= c;
   assert(arr == "abcdefghijklmnopqrstuvwxyz");

}</lang>

Delphi

<lang delphi>program atoz;

var

 ch : char;

begin

 for ch in ['a'..'z'] do
 begin
   write(ch);
 end;

end.</lang>

Output:
abcdefghijklmnopqrstuvwxyz

Elixir

<lang elixir>iex(1)> Enum.to_list(?a .. ?z) 'abcdefghijklmnopqrstuvwxyz' iex(2)> Enum.to_list(?a .. ?z) |> List.to_string "abcdefghijklmnopqrstuvwxyz"</lang>

Erlang

<lang erlang>lists:seq($a,$z).</lang>

Output:
"abcdefghijklmnopqrstuvwxyz"

F#

<lang fsharp>let lower = ['a'..'z']

printfn "%A" lower</lang>

Factor

Strings are represented as fixed-size mutable sequences of Unicode code points.

<lang factor>USING: spelling ; ! ALPHABET

ALPHABET print 0x61 0x7A [a,b] >string print

russian-alphabet-without-io ( -- str ) 0x0430 0x0450 [a,b) >string ;
russian-alphabet ( -- str ) 0x0451 6 russian-alphabet-without-io insert-nth ;

russian-alphabet print</lang>

Output:
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
абвгдеёжзийклмнопрстуфхцчшщъыьэюя

Forth

<lang Forth>\ generate a string filled with the lowercase ASCII alphabet \ RAW Forth is quite low level. Strings are simply named memory spaces in Forth. \ Typically they return an address on the Forth Stack (a pointer) with a count value in CHARs \ These examples use a string with the first byte containing the length of the string

\ We show 2 ways to load the ASCII values

create lalpha 27 chars allot \ create a string for 26 letters and count byte

]lalpha ( index -- addr ) \ word to index the string like an array
         lalpha char+ + ;       

\ method 1: use a loop

fillit ( -- )
        26 0
        do
          [char] a I +            \ calc. the ASCII value  
          I ]lalpha c!            \ store the char (c!) in the string at I
        loop
        26 lalpha c! ;            \ store the count byte at the head of the string


\ method 2: load with a string literal

Loadit s" abcdefghijklmnopqrstuvwxyz" lalpha PLACE ;</lang>

Test at the console <lang> fillit ok

lalpha count type abcdefghijklmnopqrstuvwxyz ok

loadit ok

lalpha count type abcdefghijklmnopqrstuvwxyz ok

ok

</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran> character(26) :: alpha

 integer :: i
 do i = 1, 26
   alpha(i:i) = achar(iachar('a') + i - 1)
 end do</lang>

Go

<lang go>func loweralpha() string { p := make([]byte, 26) for i := range p { p[i] = 'a' + byte(i) } return string(p) }</lang>

Groovy

<lang groovy>def lower = ('a'..'z')</lang> Test <lang groovy>assert 'abcdefghijklmnopqrstuvwxyz' == lower.join()</lang>

Haskell

<lang haskell>lower = ['a' .. 'z']

main = do

   print lower</lang>

Icon and Unicon

This example is incorrect. Please fix the code and remove this message.

Details: This code doesn't respect the spirit of this task, that asks to generate lower case letters and to do it in a reliable style, as used in very large programs.

You can just use the keyword:

&lcase

(although this technically produces a character set instead of a string, it can be used as a string, so string subscripting, generation, etc., all work).

E.g. <lang unicon>every a := put([], !&lcase) # array of 1 character per element c := create !&lcase # lazy generation of letters in sequence</lang>

J

Solution:<lang j> ([+i.@-.@-)&.(a.&i.)/'az' abcdefghijklmnopqrstuvwxyz</lang> or<lang J> u:97+i.26 abcdefghijklmnopqrstuvwxyz</lang> and, obviously, other variations are possible.

Java

<lang java>public class LowerAscii {

   public static void main(String[] args) {
       StringBuilder sb = new StringBuilder(26);
       for (char ch = 'a'; ch <= 'z'; ch++)
           sb.append(ch);
       System.out.printf("lower ascii: %s, length: %s", sb, sb.length());
   }

}</lang>

Output:

lower ascii: abcdefghijklmnopqrstuvwxyz, length: 26

JavaScript

In ES5, we can use String.fromCharCode(), which suffices for Unicode characters which can be represented with one 16 bit number.

For Unicode characters beyond this range, in ES5 we have to enter a pair of unicode number escapes.

<lang JavaScript>(function (iFrom, iTo) {

 function cRange(cFrom, cTo) {
   var iStart = cFrom.charCodeAt(0);
   return Array.apply(
     null, Array(cTo.charCodeAt(0) - iStart + 1)
   ).map(function (_, i) {
     return String.fromCharCode(iStart + i);
   });
 }
 return cRange(iFrom, iTo);

})('a', 'z');</lang>

Returns: <lang JavaScript>["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]</lang>


In ES6, the new String.FromCodePoint() method can can return 4-byte characters (such as Emoji, for example) as well as the usual 2-byte characters.

Works with: ECMAScript version 6

<lang JavaScript>var letters = [] for (var i = 97; i <= 122; i++) {

   letters.push(String.fromCodePoint(i))

}</lang>

jq

<lang jq>"az" | explode | [range( .[0]; 1+.[1] )] | implode'</lang> produces:

"abcdefghijklmnopqrstuvwxyz"

Julia

<lang Julia>['a':'z']

[c for c = 'a':'z']

string('a':'z'...)</lang>

Output:
julia> show(['a':'z'])
['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

julia> string('a':'z'...)
"abcdefghijklmnopqrstuvwxyz"

Straightforward, assuming ASCII: <lang logo>show map "char iseq 97 122</lang> Slightly less straightforward, but without the magic numbers: <lang logo>show map "char apply "iseq map "ascii [a z]</lang> Same output either way:

Output:
[a b c d e f g h i j k l m n o p q r s t u v w x y z]

Mathematica

<lang Mathematica>start = 97; lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}]</lang>

Output:
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}

Mercury

<lang mercury>:- module gen_lowercase_ascii.

- interface.
- import_module io.
- pred main(io::di, io::uo) is det.
- implementation.
- import_module char, int, list.

main(!IO) :-

   list.map(char.det_from_int, 0'a .. 0'z, Alphabet),
   io.print_line(Alphabet, !IO).
- end_module gen_lowercase_ascii.</lang>
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Nim

<lang nim># A slice just contains the first and last value let alpha: Slice[char] = 'a'..'z' echo alpha # (a: a, b: z)

  1. but can be used to check if a character is in it:

echo 'f' in alpha # true echo 'G' in alpha # false

  1. A set contains all elements as a bitvector:

let alphaSet: set[char] = {'a'..'z'} echo alphaSet # {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z} echo 'f' in alphaSet # true var someChars = {'a','f','g'} echo someChars <= alphaSet # true

import sequtils

  1. A sequence:

let alphaSeq = toSeq 'a'..'z' echo alphaSeq # @[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] echo alphaSeq[10] # k</lang>


Oforth

Oforth characters are integers. This list is a list of 26 integers <lang Oforth>seqFrom('a', 'z')</lang>

If necessary, these integers can be added to a string to have a indexed string of chars <lang Oforth>StringBuffer new seqFrom('a', 'z') apply(#<<c)</lang>

Perl

<lang Perl>print 'a'..'z'</lang>

Perl 6

<lang Perl 6>say 'a'..'z'</lang>

PHP

<lang php><?php $lower = range('a', 'z'); var_dump($lower); ?></lang>

PicoLisp

<lang>(mapcar char (range (char "a") (char "z")))</lang>

PL/I

<lang PL/I>gen: procedure options (main); /* 7 April 2014. */

  declare 1 ascii union,
            2 letters (26) character (1),
            2 iletters(26) unsigned fixed binary (8),
          letter character(1);
  declare i fixed binary;
  letters(1), letter = lowercase('A');

  do i = 2 to 26;
     iletters(i) = iletters(i-1) + 1;    
  end;
  put edit (letters) (a);

end gen;</lang> Output:

abcdefghijklmnopqrstuvwxyz

Alternative, using library: <lang> /* Accessing library lower-case ASCII (PC only). */

  letter = lowercase('A');
  i = index(collate(), letter);
  put skip list (substr(collate, i, 26));</lang>

Output:

abcdefghijklmnopqrstuvwxyz

Prolog

Works with SWI-Prolog 6.5.3 <lang Prolog>a_to_z(From, To, L) :- maplist(atom_codes, [From, To], [[C_From], [C_To]]), bagof([C], between(C_From, C_To, C), L1), maplist(atom_codes,L, L1). </lang> Output :

 ?- a_to_z(a, z, L).
L = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z].

PureBasic

<lang purebasic>Dim lower_case('z' - 'a') ;indexing goes from 0 -> 25 For i = 0 To ArraySize(lower_case())

 lower_case(i) = i + 'a'

Next</lang>

Python

<lang Python># From the standard library: from string import ascii_lowercase

  1. Generation:

lower = [chr(i) for i in range(ord('a'), ord('z') + 1)]</lang>


R

<lang R>

  1. From constants built into R:

letters </lang>

Racket

<lang racket>(define lowercase-letters (build-list 26 (lambda (x) (integer->char (+ x (char->integer #\a))))))</lang>

REXX

ASCII version

This version only works under ASCII machines   (where the values of the lowercase a through the lowercase z characters are contiguous (and consecutive). <lang rexx>/* REXX ---------------------------------------------------------------

  • 08.02.2014 Walter Pachl
  • --------------------------------------------------------------------*/

say xrange('a','z')</lang> Output:

abcdefghijklmnopqrstuvwxyz

idiomatic version

This REXX version shows how to generate an indexable string of a similar sequence (as per the lowercase ASCII characters), using a reliable style of coding.
This version also works on non-ASCII systems (such as EBCDIC) and isn't dependent on the consecutiveness nature of any particular ASCII character subsequence.
Note that on an EBCDIC system, there are 41 characters between (lowercase)   a   ──►   z     (inclusive), some of which don't have viewable/displayable glyphs. <lang rexx>/*REXX pgm creates an indexable string of lowercase ASCII characters a ──► z */ LC= /*set lowercase letters list to null*/

      do j=0  for 2**8;   _=d2c(j)       /*convert decimal  J  to character. */
      if datatype(_,'L')  then LC=LC||_  /*Lowercase?  Then add it to LC list*/
      end   /*j*/                        /* [↑]  add lowercase letters ──► LC*/

say LC /*stick a fork in it, we're all done*/</lang> output

abcdefghijklmnopqrstuvwxyz

Ruby

<lang ruby>p ('a' .. 'z').to_a p [*'a' .. 'z']</lang>

Run BASIC

<lang Runbasic>for i = asc("a") to asc("z")

print chr$(i);

next i</lang>Output:

abcdefghijklmnopqrstuvwxyz

Scala

Library: Scala

<lang scala>object Abc extends App {

 val lowAlfa = 'a' to 'z' //That's all
 // Now several tests
 assert(lowAlfa.toSeq == Seq('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
   'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'),
   "No complete lowercase alfabet.")
 assert(lowAlfa.size == 26, "No 26 characters in alfabet")
 assert(lowAlfa.start == 'a', "Character 'a' not first char! ???")
 assert(lowAlfa.head == 'a', "Character 'a' not heading! ???")
 assert(lowAlfa.head == lowAlfa(0), "Heading char is not first char.")
 assert(lowAlfa contains 'n', "Character n not present.")
 assert(lowAlfa.indexOf('n') == 13, "Character n not on the 14th position.")
 assert(lowAlfa.last == lowAlfa(25), "Expected character (z)on the last and 26th pos.")
 println(s"Successfully completed without errors. [within ${
   scala.compat.Platform.currentTime - executionStart
 } ms]")

}</lang>

Output:
Successfully completed without errors. [within 675 ms]

Process finished with exit code 0


Scheme

Works with: Gauche Scheme

<lang Scheme>(map integer->char (iota 26 (char->integer #\a)))</lang>

Output:
(#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l #\m
 #\n #\o #\p #\q #\r #\s #\t #\u #\v #\w #\x #\y #\z)

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var string: lower is "";
   var char: ch is ' ';
 begin
   for ch range 'a' to 'z' do
     lower &:= ch;
   end for;
   writeln(lower);
 end func;</lang>
Output:
abcdefghijklmnopqrstuvwxyz

Sidef

<lang ruby>var arr = 'a'..'z'; say arr.join(' ');</lang>

Standard ML

<lang sml>val lowercase_letters = List.tabulate (26, fn x => chr (x + ord #"a"));</lang>

Swift

<lang Swift>var letters = [Character]()

for i in 97...122 {

   let char = Character(UnicodeScalar(i))
   letters.append(char)

}</lang>

Tcl

The most common way of doing this in Tcl would be to use a simple literal; it's only 51 characters after all: <lang tcl>set alpha {a b c d e f g h i j k l m n o p q r s t u v w x y z}</lang> Though it could be done like this as well: <lang tcl>set alpha [apply {{} {

   scan "az" "%c%c" from to
   for {set i $from} {$i <= $to} {incr i} {
       lappend l [format "%c" $i]
   }
   return $l

}}]</lang>

UNIX Shell

In bash or ksh93 with braceexpand set: <lang sh>lower=({a..z})</lang>

In zsh with braceccl set: <lang sh>lower=({a-z})</lang>

Either way, you can display the result like this:

<lang sh>echo "${lower[@]}"</lang>

Output:
a b c d e f g h i j k l m n o p q r s t u v w x y z

VBScript

<lang vb>Function ASCII_Sequence(range) arr = Split(range,"..") For i = Asc(arr(0)) To Asc(arr(1)) ASCII_Sequence = ASCII_Sequence & Chr(i) & " " Next End Function

WScript.StdOut.Write ASCII_Sequence(WScript.Arguments(0)) WScript.StdOut.WriteLine</lang>

Output:
C:\>cscript /nologo ascii_sequence.vbs a..z
a b c d e f g h i j k l m n o p q r s t u v w x y z

C:\>cscript /nologo ascii_sequence.vbs A..F
A B C D E F

Vim Script

<lang vim>let lower = [] for c in range(0, 25)

  let lower += [nr2char(c + char2nr("a"))]

endfor</lang>

or: <lang vim>echo map(range(char2nr('a'), char2nr('z')), 'nr2char(v:val)')</lang>

zkl

<lang zkl>["a".."z"] // lasy list ["a".."z"].walk() //-->L("a","b","c","d","e",... "a".toAsc().pump(26,List,"toChar") // another way to create the list "a".toAsc().pump(26,String,"toChar") // create a string

  //-->"abcdefghijklmnopqrstuvwxyz"

Utils.Helpers.lowerLetters // string const</lang>