
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 a 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 characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
setalpha{abcdefghijkmnopqrstuvwxyz}
This creates the list in the queue
<:61:~}:000:>>&{~<:7a:-#:001:<:1:+^:000:print(Array(‘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]
In EBCDIC coding there are more than 24 characters between a and z. So we have to get rid of characters between i and j and also between r and s.
* Generate lower case alphabet - 15/10/2015LOWER CSECT USING LOWER,R15 set base register LA R7,PG pgi=@pg SR R6,R6 clear IC R6,=C'a' char='a' BCTR R6,0 char=char-1LOOP LA R6,1(R6) char=char+1 STC R6,CHAR CLI CHAR,C'i' if char>'i' BNH OK CLI CHAR,C'j' and char<'j' BL SKIP then skip CLI CHAR,C'r' if char>'r' BNH OK CLI CHAR,C's' and char<'s' BL SKIP then skipOK MVC 0(1,R7),CHAR output char LA R7,1(R7) pgi=pgi+1SKIP CLI CHAR,C'z' if char='z' BNE LOOP loop XPRNT PG,26 print buffer XR R15,R15 set return code BR R14 return to callerCHAR DS C characterPG DS CL26 buffer YREGS END LOWER
abcdefghijklmnopqrstuvwxyz
Stores the lower-case ASCII alphabet as a null-terminated string beginning at address 2000 hex. Register contents are preserved.
ASCLOW:PHA; push contents of registers that weTXA; shall be using onto the stackPHALDA#$61 ; ASCII "a"LDX#$00ALLOOP:STA$2000,XINXCLCADC#$01CMP#$7B ; have we got beyond ASCII "z"?BNEALLOOPLDA#$00 ; terminate the string with ASCII NULSTA$2000,XPLA; retrieve register contents fromTAX; the stackPLARTS; return
Stores the lower-case ASCII alphabet as a null-terminated string beginning at address 100000 hex. Register contents are preserved.
Called as a subroutine (i.e. "JSR Ascii_Low" if far away or "BSR Ascii_Low" if nearby)
Ascii_Low:MOVEM.LD0/A0,-(SP);store D0 and A0 on stackLEA$00100000,A0;could also have used MOVE.L since the address is staticMOVE.B#$61,D0;ascii "a"loop_AsciiLow:MOVE.BD0,(A0)+;store letter in address and increment pointer by 1ADDQ.B#1,D0;add 1 to D0 to get the next letterCMP.B#$7B,D0;Are we done yet? (7B is the first character after lowercase "z")BNEloop_AsciiLow;if not, loop againMOVE.B#0,(A0);store the null terminatorMOVEM.L(SP)+,D0/A0;pop D0 and A0rts
This routine takes a memory location in HL, and stores the alphabet therein the form of an$-terminated string that CP/M syscalls can use.
org100hjmptest;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Store the lowercase alphabet as a CP/M string;; ($-terminated), starting at HL.;; Destroys: b, calph:lxib,611ah; set B='a' and C=26 (counter)aloop:movm,b; store letter in memoryinrb; next letterinxh; next memory positiondcrc; one fewer letter leftjnzaloop; go do the next letter if there is onemvim,'$'; terminate the stringret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Test codetest:lxih,buf; select buffercallalph; generate alphabetlxid,buf; print string in buffermvic,9call5 rst0buf:ds27; buffer to keep the alphabet in
bits16cpu8086org100hsection.textjmpdemo;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Store the lowercase alphabet starting at [ES:DI];;;Destroys AX, CX, DIalph:movcx,13; 2*13 words = 26 bytesmovax,'ab'; Do two bytes at once.loop:stosw; Store AX at ES:DI and add 2 to DIaddax,202h; Add 2 to both bytes (CD, EF, ...)loop.loopmoval,'$'; MS-DOS string terminatorstosbret;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;demo:movdi,buf; Pointer to buffercallalph; Generate the alphabetmovdx,buf; Print the contents of the buffermovah,9int21hretsection.bssbuf:resb27; Buffer to store the alphabet in
We take an empty string, and use the "loop" word to create a new character using "'a n:+". The loop passes the current index to the code being iterated, so it starts with 0 and up to 25, adding to the "'a" - which is the numeric value of lowercase "a", and the resultant number is then appended to the string. That converts the number to the appropriate character and appends it:
""( 'a n:+ s:+ )025loop.cr
abcdefghijklmnopqrstuvwxyz
REPORTlower_case_ascii.WRITE:/to_lower(sy-abcde).
REPORTlower_case_ascii.cl_demo_output=>new()->begin_section(|Generate lower case ASCII alphabet|)->write(REDUCEstring(INIToutTYPEstringFORchar=1UNTILchar>strlen(sy-abcde)NEXTout=COND#(WHENoutIS INITIALTHENsy-abcde(1)ELSE|{out}{CONDstring(WHENchar<>strlen(sy-abcde)THENsy-abcde+char(1))}|)))->write(|Or use the system field:{sy-abcde}|)->display().
byte XProc Main() For X=97 To 122 Do Put(x) OdReturn
abcdefghijklmnopqrstuvwxyz
The following are code snippets with commentary; the code cannot be executed as is. (this comment was not made by the author of this solution]
We start with a strong type definition: A character range that can only hold lower-case letters:
typeLower_CaseisnewCharacterrange'a'..'z';
Now we define an array type and initialize the Array A of that type with the 26 letters:
typeArr_Typeisarray(Integerrange<>)ofLower_Case;A:Arr_Type(1..26):="abcdefghijklmnopqrstuvwxyz";
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:
B:Arr_Type(1..26);beginB(B'First):='a';forIinB'First..B'Last-1loopB(I+1):=Lower_Case'Succ(B(I));endloop;-- now all the B(I) are different
-- Here is the fleshed-out code using the snippets from above-- Note that I could have enhanced the output by not displaying the last comma-- December 2024, R. B. E.withAda.Text_IO;procedureGenerate_Lower_Case_ASCII_Alphabetis-- We start with a strong type definition: A character range that can only hold lower-case letters:typeLower_CaseisnewCharacterrange'a'..'z';-- Now we define an array type and initialize the Array A of that type with the 26 letters:typeArr_Typeisarray(Integerrange<>)ofLower_Case;A:Arr_Type(1..26):="abcdefghijklmnopqrstuvwxyz";-- 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:B:Arr_Type(1..26);beginB(B'First):='a';forIinB'First..B'Last-1loopB(I+1):=Lower_Case'Succ(B(I));endloop;-- now all the B(I) are differentforIinB'First..B'LastloopAda.Text_IO.Put(B(I)'Image&", ");endloop;Ada.Text_IO.New_Line;endGenerate_Lower_Case_ASCII_Alphabet;
'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',
Tested with Agena 5.0.0 Win32
# Generate lower case ASCII alphabet scope for i from abs('a') to abs('z') do printf("%c", i) od print()endabcdefghijklmnopqrstuvwxyz
Note that these samples are code fragments - to make runnable programs, add e.g.:;print( ( lc, newline ) ) to the end of each one.
ALGOL 68 Genie allows the program to be a serial clause but other compilers/interpreters may require the sample to be wrapped inBEGIN andEND to make them valid particular programs.
# 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"
Alternative version
# 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
% set lc to the lower case alphabet % string(26) lc; for c := 0 until 25 do lc( c // 1 ) := code( decode( "a" ) + c );
⎕UCS96+⍳26
-------------------- ALPHABETIC SERIES -------------------onrununlines(map(concat,¬({enumFromTo("a","z"),¬enumFromTo("🐟","🐐"),¬enumFromTo("z","a"),¬enumFromTo("α","ω")})))endrun-------------------- GENERIC FUNCTIONS --------------------- concat :: [[a]] -> [a]-- concat :: [String] -> Stringonconcat(xs)setlngtolengthofxsif0<lngandstringisclassof(item1ofxs)thensetaccto""elsesetaccto{}endifrepeatwithifrom1tolngsetacctoacc&itemiofxsendrepeataccendconcat-- enumFromTo :: Enum a => a -> a -> [a]onenumFromTo(m,n)ifclassofmisintegerthenenumFromToInt(m,n)elseenumFromToChar(m,n)endifendenumFromTo-- enumFromToChar :: Char -> Char -> [Char]onenumFromToChar(m,n)set{intM,intN}to{idofm,idofn}setxsto{}repeatwithifromintMtointNbysignum(intN-intM)setendofxstocharacteridiendrepeatreturnxsendenumFromToChar-- mReturn :: First-class m => (a -> b) -> m (a -> b)onmReturn(f)-- 2nd class handler function lifted into 1st class script wrapper.ifscriptisclassoffthenfelsescriptproperty|λ|:fendscriptendifendmReturn-- map :: (a -> b) -> [a] -> [b]onmap(f,xs)-- The list obtained by applying f-- to each element of xs.tellmReturn(f)setlngtolengthofxssetlstto{}repeatwithifrom1tolngsetendoflstto|λ|(itemiofxs,i,xs)endrepeatreturnlstendtellendmap-- signum :: Num -> Numonsignum(x)ifx<0then-1elseifx=0then0else1endifendsignum-- unlines :: [String] -> Stringonunlines(xs)-- A single string formed by the intercalation-- of a list of strings with the newline character.set{dlm,mytext item delimiters}to¬{mytext item delimiters,linefeed}setstoxsastextsetmytext item delimiterstodlmsendunlines
abcdefghijklmnopqrstuvwxyz🐟🐞🐝🐜🐛🐚🐙🐘🐗🐖🐕🐔🐓🐒🐑🐐zyxwvutsrqponmlkjihgfedcbaαβγδεζηθικλμνξοπρςστυφχψω
A minor variation would be to perform a mass conversion and character extraction at the end instead of twenty-six individualcharacter id i conversions:
setlto{}repeatwithifromidof"a"toidof"z"setendofltoiendrepeatreturncharactersofstringidl
{"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"}
(import std.String)(print string:asciiLowercase)(mut letters "")(mut c (string:ord "a"))(while (<= c (string:ord "z")) { (set letters (+ letters (string:chr c))) (set c (+ c 1)) })(print letters)abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
Uses VASM syntax.PrintString routine courtesy ofChibiakumas
Hardware: Game Boy Advance (ARM7TDMI)
This code generates the lower case ASCII set, stores it in RAM as a string literal, and prints that string to the screen.
ProgramStart:movsp,#0x03000000;Init Stack Pointermovr4,#0x04000000;DISPCNT -LCD Controlmovr2,#0x403;4= Layer 2 on / 3= ScreenMode 3strr2,[r4];hardware specific routine, activates Game Boy's bitmap modemovr0,#0x61;ASCII "a"movr2,#ramareamovr1,#26rep_inc_stosb:;repeatedly store a byte into memory, incrementing the destination and the value stored; each time.strBr0,[r2]addr0,r0,#1addr2,r2,#1subsr1,r1,#1bnerep_inc_stosbmovr0,#255strBr0,[r2];store a 255 terminator into r1movr1,#ramareablPrintString;Prints a 255-terminated string using a pre-defined bitmap font. Code omitted for brevityforever:bforever;halt the cpu
printto[:char]97..122
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
(* ****** ****** *)//// How to compile://// patscc -DATS_MEMALLOC_LIBC -o lowercase lowercase.dats//(* ****** ****** *)//#include"share/atspre_staload.hats"//(* ****** ****** *)implementmain0 () ={//val N = 26//val A =arrayref_tabulate_cloref<char>( i2sz(N), lam(i) => int2char0(char2int0('a') + sz2i(i))) (* end of [val] *)//} (* end of [main0] *)a:={}Loop,26a.Insert(Chr(A_Index+96))
Func_a2z()Local$a2z=""For$i=97To122$a2z&=Chr($i)NextReturn$a2zEndFunc
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
# syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWKBEGIN{for(i=0;i<=255;i++){c=sprintf("%c",i)if(c~/[[:lower:]]/){lower_chars=lower_charsc}}printf("%s %d: %s\n",ARGV[0],length(lower_chars),lower_chars)exit(0)}
gawk_3_1_8 26: abcdefghijklmnopqrstuvwxyzgawk_4_1_0 65: abcdefghijklmnopqrstuvwxyzƒsozªµºßàáâaäåæçèéêëìíîïdñòóôoöoùúûüy_ÿ
10REM Generate lower case ASCII alphabet20FORI=ORD("a")TOORD("z")30PRINTCHR$(I);40NEXTI50PRINT60END
abcdefghijklmnopqrstuvwxyz
L$="abcdefghijklmnopqrstuvwxyz"
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:
L$="":FORI=1TO26:L$=L$+CHR$(96+I):NEXT
REM Generate lower case ASCII alphabetAsca=ASC("a")Ascz=ASC("z")FORI=AscaTOAsczC$=CHR$(I)PRINTC$;NEXTIPRINTEND
abcdefghijklmnopqrstuvwxyz
Using the inline loop construct.
PRINT LOOP$(26, CHR$(96+_))
abcdefghijklmnopqrstuvwxyz
# generate lowercase ascii alphabet# basic256 1.1.4.0dim a$(27) # populating array for possible future usefor i = 1 to 26 a$[i] = chr(i + 96) print a$[i] + " ";next i
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
DIMlower&(25)FORi%=0TO25lower&(i%)=ASC"a"+i%NEXTEND
10fori=asc("a")toasc("z")20printchr$(i);30nexti
10FORI=ASC("A")TOASC("Z")20A$=A$+CHR$(I)30NEXT40PRINTCHR$(14):REM'SWITCH CHARACTER SET TO LOWER/UPPER CASES50PRINTA$
' FB 1.05.0 Win64' Create a string buffer to store the alphabet plus a final null byteDimalphabetAsZstring*27' ASCII codes for letters a to z are 97 to 122 respectivelyForiAsInteger=0To25alphabet[i]=i+97NextPrintalphabetPrintPrint"Press any key to quit"Sleep
abcdefghijklmnopqrstuvwxyz
TheMSX Basic solution works without any changes.
100 STRING ALPHA$*26110 LET ALPHA$=""120 FOR I=ORD("a") TO ORD("z")130 LET ALPHA$=ALPHA$&CHR$(I)140 NEXT150 PRINT ALPHA$10FORI=ASC("a")TOASC("z")20PRINTCHR$(I);30NEXTI
abcdefghijklmnopqrstuvwxyz
uses consoleint ifor i = asc("a") to asc("z") print chr(i);next iprintl cr "Enter ..."waitkeyabcdefghijklmnopqrstuvwxyz
Dimlower_case('z' - 'a') ;indexing goes from 0 -> 25Fori=0ToArraySize(lower_case())lower_case(i)=i+'a'Next
DIMa$(27)FORi=1to26LETa$(i)=CHR$(i+96)PRINTa$(i);NEXTiEND
for i = asc("a") to asc("z") print chr$(i);next iOutput:
abcdefghijklmnopqrstuvwxyz
DIMa$(27)FORi=1to26LETa$(i)=CHR$(i+96)PRINTa$(i);NEXTiEND
For x= ORD("a") To ORD("z") : @(x - ORD("a")) = x : NextOptionExplicitSubMain_Lower_Case_Ascii_Alphabet()DimAlpha()AsStringAlpha=Alphabet(97,122)Debug.PrintJoin(Alpha,", ")EndSubFunctionAlphabet(FirstAsciiAsByte,LastAsciiAsByte)AsString()DimstrarrTemp()AsString,i&ReDimstrarrTemp(0ToLastAscii-FirstAscii)Fori=FirstAsciiToLastAsciistrarrTemp(i-FirstAscii)=Chr(i)NextAlphabet=strarrTempErasestrarrTempEndFunction
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
FunctionASCII_Sequence(range)arr=Split(range,"..")Fori=Asc(arr(0))ToAsc(arr(1))ASCII_Sequence=ASCII_Sequence&Chr(i)&" "NextEndFunctionWScript.StdOut.WriteASCII_Sequence(WScript.Arguments(0))WScript.StdOut.WriteLine
C:\>cscript /nologo ascii_sequence.vbs a..za b c d e f g h i j k l m n o p q r s t u v w x y zC:\>cscript /nologo ascii_sequence.vbs A..FA B C D E F
The#VBA example works in VB6 as well, without any change.
UsedAsc(Char) [returns Integer value of Char passed] andChr(Integer) [returns Char value of Integer passed] functions.
String.Join() is used to print the list, converted to array, without looping through it.
ModuleLowerASCIISubMain()DimalphabetsAsNewList(OfChar)ForiAsInteger=Asc("a")ToAsc("z")alphabets.Add(Chr(i))NextConsole.WriteLine(String.Join("",alphabets.ToArray))EndSubEndModule
abcdefghijklmnopqrstuvwxyz
PROGRAM"progname"VERSION"0.0000"DECLAREFUNCTIONEntry()FUNCTIONEntry()DIMa$[27]FORi=1TO26a$[i]=CHR$(i+96)PRINTa$[i];NEXTiENDFUNCTIONENDPROGRAM
for i = asc("a") to asc("z") print chr$(i);next i10DIMl$(26):LETinit=CODE"a"-120FORi=1TO2630LETl$(i)=CHR$(init+i)40NEXTi50PRINTl$
@echo offsetlocal enabledelayedexpansion:: This code appends the ASCII characters from 97-122 to %alphabet%, removing any room for error.for/l%%iin(97,1,122)do( cmd /c exit%%iset"alphabet=!alphabet! !=exitcodeAscii!")echo%alphabet%pause>nul
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
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.
0"z":>"a"`#v_>:#,_$@^:-1:<
'a'+↕26
a:?seq:?c& whl ' ( chr$(asc$!c+1):~>z:?c & !seq !c:?seq )& !seq
Make room for 26 characters>>>>>>>>>>>>>>>>>>>>>>>>>>Set counter to 26>>++++++++++++++++++++++++++Generate the numbers 1 to 26[-<< Decrement counter[+<] Add one to each nonzero cell moving right to left+ Add one to first zero cell encountered[>]> Return head to counter]<<Add 96 to each cell[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<]Print each cell>[.>]++++++++++. \n
Uncommented:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>++++++++++++++++++++++++++[-<<[+<]+[>]>]<<[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<]>[.>]++++++++++.
A smaller and faster solution:
++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[->+.<]
abcdefghijklmnopqrstuvwxyz
blsq ) @azr\shabcdefghijklmnopqrstuvwxyz
#include<stdlib.h>#define N 26intmain(){unsignedcharlower[N];for(size_ti=0;i<N;i++){lower[i]=i+'a';}returnEXIT_SUCCESS;}
Simple Linq 1 liner solution
usingSystem;usingSystem.Linq;internalclassProgram{privatestaticvoidMain(){Console.WriteLine(String.Concat(Enumerable.Range('a',26).Select(c=>(char)c)));}}
abcdefghijklmnopqrstuvwxyz
Old style Property and enumerable based solution
namespaceRosettaCode.GenerateLowerCaseASCIIAlphabet{usingSystem;usingSystem.Collections.Generic;internalclassProgram{privatestaticIEnumerable<char>Alphabet{get{for(varcharacter='a';character<='z';character++){yieldreturncharacter;}}}privatestaticvoidMain(){Console.WriteLine(string.Join(string.Empty,Alphabet));}}}
abcdefghijklmnopqrstuvwxyz
C++ can do the task in the identical way as C, or else, it can use a STL function.
#include<string>#include<numeric>intmain(){std::stringlower(26,' ');std::iota(lower.begin(),lower.end(),'a');}
(map char(range(int\a)(inc(int\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)
alph = proc () returns (string) a: int := char$c2i('a') letters: array[char] := array[char]$predict(1,26) for i: int in int$from_to(0, 25) do array[char]$addh(letters, char$i2c(a + i)) end return(string$ac2s(letters))end alph% teststart_up = proc () stream$putl(stream$primary_output(), alph())end start_upabcdefghijklmnopqrstuvwxyz
Strings in COBOL are mutable and can be subscripted: each time we go round the loop, we assign to a one-character-long section of the string we are building.
identificationdivision.program-id.lower-case-alphabet-program.data division.working-storagesection.01 ascii-lower-case. 05lower-case-alphabetpic a(26). 05character-codepic 999. 05loop-counterpic 99.proceduredivision.control-paragraph. performadd-next-letter-paragraphvaryingloop-counterfrom1by1untilloop-counterisgreaterthan26. displaylower-case-alphabetuponconsole. stoprun.add-next-letter-paragraph. add97toloop-countergivingcharacter-code. movefunctionchar(character-code)tolower-case-alphabet(loop-counter:1).
abcdefghijklmnopqrstuvwxyz
(String.fromCharCode(x)forxin[97..122])
dimalphabet$of26fori:=1to26alphabet$(i):=chr$(ord("a")-1+i)endforiprintalphabet$
abcdefghijklmnopqrstuvwxyz
;; as a list
(defvar*lower*(loopwitha=(char-code#\a)foribelow26collect(code-char(+ai))))
;; as a string
(defvar*lowercase-alphabet-string*(map'string#'code-char(loopforcfrom(char-code#\a)to(char-code#\z)collectc))"The 26 lower case letters in alphabetical order.")
;; verify
(assert(=26(length*lowercase-alphabet-string*)(length*lower*)))(assert(every#'char<*lowercase-alphabet-string*(subseq*lowercase-alphabet-string*1)))(assert(apply#'char<*lower*))(assert(string=*lowercase-alphabet-string*(coerce*lower*'string)))
include "cowgol.coh";# Generate the alphabet and store it at the given location# It is assumed that there is enough space (27 bytes)sub alph(buf: [uint8]): (out: [uint8]) is out := buf; var letter: uint8 := 'a'; while letter <= 'z' loop [buf] := letter; letter := letter + 1; buf := @next buf; end loop; [buf] := 0;end sub;# Use the subroutine to print the alphabetvar buf: uint8[27]; # make room for the alphabetprint(alph(&buf as [uint8]));
abcdefghijklmnopqrstuvwxyz
('a'..'z').to_a# => ['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']
The lower case ASCII letters of the Phobos standard library:
importstd.ascii:lowercase;voidmain(){}
The generation of the ASCII alphabet array:
voidmain(){char['z'-'a'+1]arr;foreach(immutablei,refc;arr)c='a'+i;}
An alternative version:
voidmain(){importstd.range,std.algorithm,std.array;char[26]arr=26.iota.map!(i=>cast(char)('a'+i)).array;}
Another version:
voidmain(){char[]arr;foreach(immutablecharc;'a'..'z'+1)arr~=c;assert(arr=="abcdefghijklmnopqrstuvwxyz");}
voidmain(){List<String>lower=List.generate(26,(index)=>String.fromCharCode(97+index));print(lower);}
[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]
Construct the numerical representation of the desired output and print it.
122 [ d 1 - d 97<L 256 * + ] d sL x P
Output:
abcdefghijklmnopqrstuvwxyz
programatoz;varch:char;beginforchin['a'..'z']dobeginwrite(ch);end;end.
abcdefghijklmnopqrstuvwxyz
/* Generate the lowercase alphabet and store it in a buffer */proc alph(*char buf) *char: channel output text ch; char letter; open(ch, buf); for letter from 'a' upto 'z' do write(ch; letter) od; close(ch); bufcorp/* Use the function to print the alphabet */proc main() void: [27] char buf; /* one byte extra for the string terminator */ writeln(alph(&buf[0]))corp
abcdefghijklmnopqrstuvwxyz
selectarray_agg(chr(ix::INT)orderbyix)aslowercasefromunnest(range(ascii('a'),1+ascii('z')))_(ix);
or equivalently as a one-liner:
selectlist_transform(generate_series(ascii('a'),ascii('z')),x->chr(x::INT))aslowercase;
┌────────────────────────────────────────────────────────────────────────────────┐│ lowercase ││ varchar[] │├────────────────────────────────────────────────────────────────────────────────┤│ [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] │└────────────────────────────────────────────────────────────────────────────────┘
In DUP, strings between double quotes are stored in a numerically addressed array. The integer before the first" which gets pushed on the data stack, defines the cell address in which the ASCII value of first character of the string will be stored. All following characters will be stored like an array as values in the following cells. At the end, DUP pushes the length of the string on the data stack.
0"abcdefghijklmnopqrstuvwxyz" {store character values of string in cells 0..length of string-1}26[$][^^-;,1-]# {Loop from 26-26 to 26-0, print the respective cell contents to STDOUT}Output:
abcdefghijklmnopqrstuvwxyz
Generates a lazy sequence and prints it to a standard output:
print << ('a'..'z').ToArray()# Generated on an arrayfor i = 97 to 122 alphabet$[] &= strchar i.print alphabet$[]# Generated on a stringfor i = 97 to 122 alphabet$ &= strchar i.print alphabet$
;; 1)(define\a(first(string->unicode"a")))(for/list((i25))(unicode->string(+i\a)))→(abcdefghijklmnopqrstuvwxy);;2) using a sequence(lib'sequences)(take["a".."z"]26)→(abcdefghijklmnopqrstuvwxyz); or(for/string((letter["a".."z"]))letter)→abcdefghijklmnopqrstuvwxyz
ELENA 6.x :
import extensions;import system'collections; singleton Alphabet : Enumerable{ Enumerator enumerator() = new Enumerator { char? current; get Value() = current; bool next() { if (nil==current) { current := $97 } else if (current != $122) { current := (current.toInt() + 1).toChar() } else { ^ false }; ^ true } reset() { current := nil } enumerable() = self; };} public Program(){ Console.printLine(Alphabet)}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
iex(1)>Enum.to_list(?a..?z)'abcdefghijklmnopqrstuvwxyz'iex(2)>Enum.to_list(?a..?z)|>List.to_string"abcdefghijklmnopqrstuvwxyz"
lists:seq($a,$z).
"abcdefghijklmnopqrstuvwxyz"
Binding the nameshowAlphabet to the following lambda expression in the Name Manager of the Excel WorkBook:
(SeeLAMBDA: The ultimate Excel worksheet function)
showAlphabet=LAMBDA(az,ENUMFROMTOCHAR(MID(az,1,1))(MID(az,2,1)))
and also assuming the following generic binding in the Name Manager for the WorkBook:
ENUMFROMTOCHAR=LAMBDA(a,LAMBDA(z,LET(aCode,UNICODE(a),zCode,UNICODE(z),UNICHAR(IF(zCode>=aCode,SEQUENCE(1,1+zCode-aCode,aCode,1),SEQUENCE(1,1+aCode-zCode,aCode,-1))))))
The formula in cell B2, for example, defines an array which populates the whole rangeB2:AA2
| fx | =showAlphabet(A2) | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 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 | AA | AB | ||
| 1 | From to | ||||||||||||||||||||||||||||
| 2 | az | 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 | ||
| 3 | αω | α | β | γ | δ | ε | ζ | η | θ | ι | κ | λ | μ | ν | ξ | ο | π | ρ | ς | σ | τ | υ | φ | χ | ψ | ω | |||
| 4 | את | א | ב | ג | ד | ה | ו | ז | ח | ט | י | ך | כ | ל | ם | מ | ן | נ | ס | ע | ף | פ | ץ | צ | ק | ר | ש | ת | |
| 5 | תא | ת | ש | ר | ק | צ | ץ | פ | ף | ע | ס | נ | ן | מ | ם | ל | כ | ך | י | ט | ח | ז | ו | ה | ד | ג | ב | א | |
| 6 | za | z | y | x | w | v | u | t | s | r | q | p | o | n | m | l | k | j | i | h | g | f | e | d | c | b | a | ||
| 7 | ωα | ω | ψ | χ | φ | υ | τ | σ | ς | ρ | π | ο | ξ | ν | μ | λ | κ | ι | θ | η | ζ | ε | δ | γ | β | α | |||
letlower=['a'..'z']printfn"%A"lower
Strings are represented as fixed-size mutable sequences of Unicode code points.
USING:spelling;! ALPHABETALPHABETprint0x61 0x7A[a,b]>stringprint:russian-alphabet-without-io(--str)0x0430 0x0450[a,b)>string;:russian-alphabet(--str)0x0451 6russian-alphabet-without-ioinsert-nth;russian-alphabetprint
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzабвгдеёжзийклмнопрстуфхцчшщъыьэюя
'a[$'z>~][$,1+]#%
abcdefghijklmnopqrstuvwxyz
Array locase[1,26];[locase]:=[<i=1,26>'a'+i-1];!([locase:char);
abcdefghijklmnopqrstuvwxyz
Generate a string filled with the lowercase ASCII alphabet
:printit260do[char]aI+emitloop;
Or coded another way
:printit2[char]z1+[char]adoIemitloop;
We could do something more complicated and allocate space for a string and fill it.Two methods are demonstrated below
createlalpha27charsallot\ create a string in memory for 26 letters and count byte:]lalpha( index -- addr )\ index the string like an array (return an address)lalphachar++;\ method 1: fill memory with ascii values using a loop:fillit( -- )260do[char]aI+\ calc. the ASCII value, leave on the stackI]lalphac!\ store the value on stack in the string at index Iloop26lalphac!;\ store the count byte at the head of the string\ method 2: load with a string literal:Loadits"abcdefghijklmnopqrstuvwxyz"lalphaPLACE;
Test at the console
printit abcdefghijklmnopqrstuvwxyz okfillit oklalpha count type abcdefghijklmnopqrstuvwxyz oklalpha count erase oklalpha count type okloadit oklalpha count type abcdefghijklmnopqrstuvwxyz ok
character(26)::alphainteger::idoi=1,26alpha(i:i)=achar(iachar('a')+i-1)end do
The following produces a lazy enumerating sequence of the characters.
map["char", char["a"] to char["z"]]
To produce a non-lazy array of the characters, you can wrap the above in atoArray call:
toArray[map["char", char["a"] to char["z"]]]
#k 'a 'z ++ {|| {} print SPACE |} NL enda 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
###sysinclude standard.uh#k 'a 'z ++ {{ , {{}} print SPACE }} NL enda 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
long ifor i = asc("a") to asc("z") print chr$(i);nextHandleEventsabcdefghijklmnopqrstuvwxyz
Click this link to run this code
PublicSubMain()DimsiCountAsShortForsiCount=Asc("a")ToAsc("z")PrintChr(siCount);NextEnd
Output:
abcdefghijklmnopqrstuvwxyz
funcloweralpha()string{p:=make([]byte,26)fori:=rangep{p[i]='a'+byte(i)}returnstring(p)}
'z'0=), 'a'0=> ''+
abcdefghijklmnopqrstuvwxyz
deflower=('a'..'z')
Test
assert'abcdefghijklmnopqrstuvwxyz'==lower.join('')
lower=['a'..'z']main=printlower
Or, equivalently:
alpha::Stringalpha=enumFromTo'a''z'main::IO()main=printalpha
"abcdefghijklmnopqrstuvwxyz"
`(list cord)`(gulf 97 122)
> `(list cord)`(gulf 97 122)<|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|>
import Algorithms as algo;import Text as text;main() { print( "{}\n".format( text.character_class( text.CHARACTER_CLASS.LOWER_CASE_LETTER ) ) ); print( "{}\n".format( algo.materialize( algo.map( algo.range( integer( 'a' ), integer( 'z' ) + 1 ), character ), string ) ) );}abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
You can just use the keyword:
&lcase
(although this technically produces a character set instead of a string, it can be usedas a string, so string subscripting, generation, etc., all work).
E.g.
everya:=put([],!&lcase)# array of 1 character per elementc:=create!&lcase# lazy generation of letters in sequence
procedurelower_case_letters()# entry point for function lower_case_lettersreturn&lcase# returning lower caser letters represented by the set &lcaseendproceduremain(param)# main procedure as entry pointwrite(lower_case_letters())# output of result of function lower_case_letters()end
(-> (map char-code "az") (adj _ inc) (.. range) (map char-code))
["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"]
Solution:
thru=:<.+i.@(+*)@-~thru&.(a.&i.)/'az'abcdefghijklmnopqrstuvwxyz
or
u:97+i.26abcdefghijklmnopqrstuvwxyz
or
([-.toupper)a.abcdefghijklmnopqrstuvwxyz
and, obviously, other variations are possible.
char[]lowerAlphabet(){char[]letters=newchar[26];for(intcode=97;code<123;code++)letters[code-97]=(char)code;returnletters;}
abcdefghijklmnopqrstuvwxyz
An alternate implementation
publicclassLowerAscii{publicstaticvoidmain(String[]args){StringBuildersb=newStringBuilder(26);for(charch='a';ch<='z';ch++)sb.append(ch);System.out.printf("lower ascii: %s, length: %s",sb,sb.length());}}
Output:
lower ascii: abcdefghijklmnopqrstuvwxyz, length: 26
In ES5, we can useString.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.
(function(cFrom,cTo){functioncRange(cFrom,cTo){variStart=cFrom.charCodeAt(0);returnArray.apply(null,Array(cTo.charCodeAt(0)-iStart+1)).map(function(_,i){returnString.fromCharCode(iStart+i);});}returncRange(cFrom,cTo);})('a','z');
Returns:
["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"]
In ES6, the newString.fromCodePoint() method can can return 4-byte characters (such as Emoji, for example) as well as the usual 2-byte characters.
(function(lstRanges){functioncRange(cFrom,cTo){variStart=cFrom.codePointAt(0);returnArray.apply(null,Array(cTo.codePointAt(0)-iStart+1)).map(function(_,i){returnString.fromCodePoint(iStart+i);});}returnlstRanges.map(function(lst){returncRange(lst[0],lst[1]);});})([['a','z'],['🐐','🐟']]);
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"],["🐐","🐑","🐒","🐓","🐔","🐕","🐖","🐗","🐘","🐙","🐚","🐛","🐜","🐝","🐞","🐟"]]
varletters=[]for(vari=97;i<=122;i++){letters.push(String.fromCodePoint(i))}
Or, if we want to write a more general ES6 function:
(()=>{// enumFromTo :: Enum a => a -> a -> [a]constenumFromTo=(m,n)=>{const[intM,intN]=[m,n].map(fromEnum),f=typeofm==='string'?((_,i)=>chr(intM+i)):(_,i)=>intM+i;returnArray.from({length:Math.floor(intN-intM)+1},f);};// GENERIC FUNCTIONS ------------------------------------------------------// compose :: (b -> c) -> (a -> b) -> (a -> c)constcompose=(f,g)=>x=>f(g(x));// chr :: Int -> Charconstchr=x=>String.fromCodePoint(x);// ord :: Char -> Intconstord=c=>c.codePointAt(0);// fromEnum :: Enum a => a -> IntconstfromEnum=x=>{consttype=typeofx;returntype==='boolean'?(x?1:0):type==='string'?ord(x):x;};// map :: (a -> b) -> [a] -> [b]constmap=(f,xs)=>xs.map(f);// show :: a -> Stringconstshow=x=>JSON.stringify(x);// uncurry :: Function -> Functionconstuncurry=f=>args=>f.apply(null,args);// unlines :: [String] -> Stringconstunlines=xs=>xs.join('\n');// unwords :: [String] -> Stringconstunwords=xs=>xs.join(' ');// TEST -------------------------------------------------------------------returnunlines(map(compose(unwords,uncurry(enumFromTo)),[['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α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ υ φ χ ψ ωא ב ג ד ה ו ז ח ט י ך כ ל ם מ ן נ ס ע ף פ ץ צ ק ר ש ת🐐 🐑 🐒 🐓 🐔 🐕 🐖 🐗 🐘 🐙 🐚 🐛 🐜 🐝 🐞 🐟
'a ['z =] ["" cons] [dup succ] [cons] linrec.
"az" | explode | [range( .[0]; 1+.[1] )] | implode'
produces:
"abcdefghijklmnopqrstuvwxyz"
Comment written by someone who is not the submitter of the above code:
I had to remove the trailing single quote to make it work for me.
The "jq", "gojq" and "jaq" apps (from MacPorts) all worked great on my Mac after I removed the trailing quote.
/* Generate the lower case alphabet with Jsish, assume ASCII */varletterA="a".charCodeAt(0);varlowers=Array(26);for(vari=letterA;i<letterA+26;i++){lowers[i-letterA]=Util.fromCharCode(i);}puts(lowers);puts(lowers.join(''));puts(lowers.length);/*=!EXPECTSTART!=[ "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" ]abcdefghijklmnopqrstuvwxyz26=!EXPECTEND!=*/
prompt$ jsish generate-lowers.jsi[ "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" ]abcdefghijklmnopqrstuvwxyz26prompt$ jsish -u generate-lowers.jsi[PASS] generate-lowers.jsi
@showcollect('a':'z')@showjoin('a':'z')
collect('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']join('a':'z') = "abcdefghijklmnopqrstuvwxyz"`c$ casts a list of integers to a string of characters;!26 produces a list of the integers from 0 to 25. So the lower-case ASCII alphabet can be generated using:
`c$97+!26
"abcdefghijklmnopqrstuvwxyz"
a(55*|:1+)
// version 1.3.72funmain(){valalphabet=CharArray(26){(it+97).toChar()}.joinToString("")println(alphabet)}
abcdefghijklmnopqrstuvwxyz
1)Wedefinecode2char&char2codeasprimitives:{scriptLAMBDATALK.DICT["char2code"]=function(){varargs=arguments[0].trim();returnargs.charCodeAt(0);};LAMBDATALK.DICT["code2char"]=function(){varargs=arguments[0].trim();returnString.fromCharCode(args);};}2)andweusethem:{S.mapcode2char{S.serie{char2codea}{char2codez}}}->abcdefghijklmnopqrstuvwxyz{S.mapcode2char{S.serie{char2code0}{char2code9}}}->0123456789
&alphabet = fn.arrayGenerateFrom(fn.combBX(fn.char, fn.add, a), 26)fn.println(&alphabet)# As string (Strings are called text in Lang)$alphabetText = fn.join(\e, &alphabet)fn.println($alphabetText)
[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]abcdefghijklmnopqrstuvwxyz
.ORIG 0x3000 LD R0,ASCIIa LD R1,ASCIIz NOT R1,R1LOOP OUT ADD R0,R0,1 ADD R2,R0,R1 BRN LOOP HALTASCIIa .FILL 0x61ASCIIz .FILL 0x7A
Output:
abcdefghijklmnopqrstuvwxyz
alphabet = []repeat with i = 97 to 122 alphabet.add(numtochar(i))end repeatput alphabet-- ["a", "b", "c", ... , "x", "y", "z"]
Straightforward, assuming ASCII:
show map "char iseq 97 122
Slightly less straightforward, but without the magic numbers:
show map "char apply "iseq map "ascii [a z]
Same output either way:
[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]
function getAlphabet () local letters = {} for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end return lettersendlocal alpha = getAlphabet()print(alpha[25] .. alpha[1] .. alpha[25])yay
#!/usr/bin/env luajitlocal function ascii(f,t) local tab={} for i=f,t do tab[#tab+1]=string.char(i) endreturn table.concat(tab)endprint(ascii(97,122))> ./lowercaseascii.lua abcdefghijklmnopqrstuvwxyz
\\ old style Basic, including a Binary.Or() functionModule OldStyle { 10 LET A$="" 20 DEF FNUP$(I)=""""+CHR$(BINARY.OR(I, 32))+"""" 30 FOR I=ASC("A") TO ASC("Y") 40 LET A$= A$ + FNUP$(I, 32)+", " 50 NEXT I 60 LET A$ = A$+ FNUP$(I, 32) 70 PRINT A$}CALL OldStyleModule new_style {a=("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")map1= lambda ->{push binary.or(asc(letter$), 32)}map2= lambda ->{push chr$(number)}Print """"+a#map(map1, map2)#str$({", "})+""""}new_style"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"
=={{header|Maple}}==<syntaxhighlight lang="maple">seq(StringTools:-Char(c), c = 97 .. 122);</syntaxhighlight>{{Out}}<pre>"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"Note:":=" is the definition operator"=" is the evaluation operator
The actual Mathcad worksheet is athttps://community.ptc.com/t5/PTC-Mathcad/Rosetta-Code-Generate-Lower-Case-ASCII-Alphabet/m-p/670829#M190552
The Haskell-like '--' marker preceding each comment is not necessary in Mathcad, and is only there to indicate text rather than an expression.
Method 1: Using a Range Variable.
-- user-defined function that returns the ASCII code for string character ch.code(ch):=str2vec(ch)[0-- number of lower-case ASCII charactersN:=26-- range variable covering the relative indices of the lower-case characters within the ASCII character set (0 = 'a', 25 = 'z').k:=0..N-1-- ASCII code for letter 'a' (a=97 ).a:=code("a")-- iterate over k to produce a vector of lower case ASCII character codeslcCodes[k:=k+a-- convert vector to string of ordered ASCII lower-case characters.lcString:=vec2str(lcCodes)lcString="abcdefghijklmnopqrstuvwxyz" -- Characters are indexable within the string; for example: substr(lcString,3,1)="d"Method 2: Using a Function.
-- Mathcad Express lacks the programming capability of Mathcad Prime, so uses the built-in if function to implement a recursive solution (if(predicate,true expr, false expr)). -- char(cd): return the string character with code cd.char(cd):=vec2str([cd])-- charseq(m,n): return a string containing an ordered list of the characters whose codes lie between m and n, inclusive.charseq(m,n):=if(m>=n,char(m),concat(char(m),charseq(m+1,n)))charseq(code("a"),code("z"))="abcdefghijklmnopqrstuvwxyz"charseq(code("A"),code("Z"))="ABCDEFGHIJKLMNOPQRSTUVWXYZ"charseq(code("0"),code("9"))="0123456789"charseq(code("а"),code("я"))="абвгдежзийклмнопрстуфхцчшщъыьэюя"charseq(code("α"),code("ω"))="αβγδεζηθικλμνξοπρςστυφχψω"start = 97;lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}]{"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"}'a':'z'
or alternatively
char(96+[1:26])
abcdefghijklmnopqrstuvwxyz
delete([], makelist(if(alphacharp(ascii(i))) then parse_string(ascii(i)) else [], i, 96, 122));
[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]
:- 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.
['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']
letters = []for i in range(code("a"), code("z")) letters.push char(i)end forprint letters["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"]
main:li $t0,'a'li $t1,26loop:jal PrintChar ;prints the low 8 bits of $t0 as an ascii character (unimplemented routine)nop ;branch delay slotsubiu $t1,1bne $t1,loopaddiu $t0,1end_program:j end_program ;halt the cpu - we're donenop
MODULE GenerASCII;(* Generate lower case ASCII alphabet *)FROM STextIO IMPORT WriteLn, WriteString;VAR C: CHAR;BEGIN FOR C := "a" TO "z" DO WriteString(C) END; WriteLnEND GenerASCII.
abcdefghijklmnopqrstuvwxyz
LOWASCMIN set lowstr = "" for i = 97:1:122 set delim = $select(i=97:"",1:",") set lowstr = lowstr_delim_$char(i) write lowstr quit
SAMPLES>DO ^LOWASCMINa,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
LONGSET D="" FOR X=97:1:122 WRITE D,$C(X) SET D=","WRITE ! QUIT;SHORTS D="" F X=97:1:122 W D,$C(X) S D=","W ! Q
MGR>DO LONGa,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 MGR>D SHORTa,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
lowercase = list()for i in range(ord("a"), ord("z")) lowercase.append(chr(i))endprintln lowercase[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]
/** <doc>Generate lower case ASCII, in Neko</doc>**/var slot = 25var generated = $smake(slot + 1)var lower_a = $sget("a", 0)/* 'a'+25 down to 'a'+0 */while slot >= 0 { $sset(generated, slot, slot + lower_a) slot -= 1}$print(generated, "\n")prompt$ nekoc generate-lower.nekoprompt$ neko generate-lower.nabcdefghijklmnopqrstuvwxyz
lower_case_ascii = {code_char(c) : c in [97:123]};Since NetLogo has no "ASC" type reporters, we will have to enumerate the characters.To make an omission easier to detect, we use a phrase, instead of a listSince the phrase has duplicates and spaces, we use other list tools to produce just the sorted alphabet
to-report alphabet-lower let sample "sphinx of black quartz judge my vow" let alphabet sort remove-duplicates remove " " n-values length sample [ c -> item c sample ] if length alphabet != 26 [ user-message "ERROR: invalid sample for alphabet function" ] report alphabetend
observer> print alphabet-lower[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]observer> write alphabet-lower ["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"]
# A slice just contains the first and last valuelet alpha: Slice[char] = 'a'..'z'echo alpha # (a: a, b: z)# but can be used to check if a character is in it:echo 'f' in alpha # trueecho 'G' in alpha # false# 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 # truevar someChars = {'a','f','g'}echo someChars <= alphaSet # trueimport sequtils# 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] # kseq char a z
function : Main(args : String[]) ~ Nil { buffer := ""; for(i := 'a'; i <= 'z'; i += 1;) { buffer += i->As(Char); }; buffer->PrintLine();}# Array.make 26 'a' |> Array.mapi (fun i c -> int_of_char c + i |> char_of_int);;- : char array =[|'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'|]
Alternative version:
Array.init 26 (fun x -> char_of_int (x + int_of_char 'a'))
Oforth characters are integers. This list is a list of 26 integers
'a' 'z' seqFrom
If necessary, these integers can be added to a string to have a indexed string of chars
StringBuffer new 'a' 'z' seqFrom apply(#<<c)
Strchr(Vecsmall([97..122]))
Output:
"abcdefghijklmnopqrstuvwxyz"
See alsoDelphi.
program lowerCaseAscii(input, output, stdErr);varalphabet: set of char;begin// as per ISO 7185, 'a'..'z' do not necessarily have to be contiguousalphabet := ['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'];end.
One can useset constructors like inDelphi.alphabet’s type will beset of char.
program lowerCaseAscii(input, output, stdErr);constalphabet = ['a'..'z'];beginend.
Note, Pascal does not define that the letters A through Z are contiguous, the set constructor above assumes that, though.However, the FPC – the FreePascal compiler – virtually only works on systems, that use at least ASCII as common denominator.
program generascii;(* Generate lower case ASCII alphabet *) var c: char;begin for c := 'a' to 'z' do write(c); writelnend.
abcdefghijklmnopqrstuvwxyz
##var a := Arr('a'..'z');a.Println;var s := ('a'..'z').JoinToString(' ');;s.Printlnabcdefghijklmnopqrstuvwxyza 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
print 'a'..'z'
withjavascript_semanticsstringaz=""forch='a'to'z'doaz&=chendfor?az?tagset('z','a')?tagstart('a',26)
Using tagset() is obviously easier, but you have to remember its parameters are (finish,start=1,step=1), that way round so that startcan be omitted and default to 1 (ditto step). tagstart() wants a length, though you could use 'z'-'a'+1 in place of the 26.
In Phix there is really not much difference between 1..26 and 'a'..'z', and noneat all between 'a'..'z' and 97..122.
"abcdefghijklmnopqrstuvwxyz""abcdefghijklmnopqrstuvwxyz""abcdefghijklmnopqrstuvwxyz"
0 tolist'a' 'z' 2 tolistfor tochar 0 putendforprint
Simplest
include ..\Utilitys.pmt( 'a' 'z' ) for tochar print endfor
<?php$lower = range('a', 'z');var_dump($lower);?>main => Alpha1 = (0'a..0'z).map(chr), println(Alpha1), Alpha2 = [chr(I) : I in 97..122], println(Alpha2).
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
(mapcar char (range (char "a") (char "z")))
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;Output:
abcdefghijklmnopqrstuvwxyz
Alternative, using library:
/* Accessing library lower-case ASCII (PC only). */ letter = lowercase('A'); i = index(collate(), letter); put skip list (substr(collate, i, 26));Output:
abcdefghijklmnopqrstuvwxyz
100H: /* PRINT THE LOWERCASE LETTERS */ /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END; /* CONSOLE OUTPUT ROUTINES */ PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; /* TASK */ DECLARE C BYTE, LC ( 27 )BYTE; DO C = 0 TO 25; LC( C ) = C + 32 + 'A'; END; LC( LAST( LC ) ) = '$'; /* STRING TERMINATOR */ CALL PR$STRING( .LC );EOF
abcdefghijklmnopqrstuvwxyz
Declare sbAlphabet varchar2(100);Begin For nuI in 97..122 loop if sbAlphabet is null then sbAlphabet:=chr(nuI); Else sbAlphabet:=sbAlphabet||','||chr(nuI); End if; End loop; Dbms_Output.Put_Line(sbAlphabet);End;
Output:
PL/SQL block, executed in 0 msa,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,zTotal execution time 16 ms
To run:Start up.Generate the lowercase ASCII alphabet giving a string.Write the string on the console.Wait for the escape key.Shut down.To generate the lowercase ASCII alphabet giving a string:Put the little-a byte into a letter.Loop.Append the letter to the string.If the letter is the little-z byte, exit.Add 1 to the letter.Repeat.
abcdefghijklmnopqrstuvwxyz
alpha = range(97,122) :reduce(|a,v|->a..string.char(v),"")print(alpha)
abcdefghijklmnopqrstuvwxyz
$asString = 97..122 | ForEach-Object -Begin {$asArray = @()} -Process {$asArray += [char]$_} -End {$asArray -join('')}$asStringabcdefghijklmnopqrstuvwxyz
$asArray
abcdefghijklmnopqrstuvwxyz
Alternative:
-join [Char[]] (97..122)
abcdefghijklmnopqrstuvwxyz
Alternative as of PowerShell-v6.0.0rc:
-join ('a'..'z')abcdefghijklmnopqrstuvwxyz
Works with SWI-Prolog 6.5.3
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).
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].
# From the standard library:from string import ascii_lowercase# Generation:lower = [chr(i) for i in range(ord('a'), ord('z') + 1)]Or, as a particular instance of a more general enumeration pattern:
'''Enumeration a-z'''from inspect import signatureimport enum# TEST ----------------------------------------------------def main(): '''Testing particular instances of a general pattern: ''' print( fTable(__doc__ + ':\n')(repr)(showList)( uncurry(enumFromTo) )([ ('a', 'z'), ('α', 'ω'), ('א', 'ת'), (1, 10), (round((5**(1 / 2) - 1) / 2, 5), 5), ('🌱', '🍂') ]) )# GENERIC -------------------------------------------------# enumFromTo :: Enum a => a -> a -> [a]def enumFromTo(m): '''Enumeration of values [m..n]''' def go(x, y): t = type(m) i = fromEnum(x) d = 0 if t != float else (x - i) return list(map( lambda x: toEnum(t)(d + x), range(i, 1 + fromEnum(y)) ) if int != t else range(x, 1 + y)) return lambda n: go(m, n)# fromEnum :: Enum a => a -> Intdef fromEnum(x): '''Index integer for enumerable value.''' Enum = enum.Enum return ord(x) if isinstance(x, str) else ( x.value if isinstance(x, Enum) else int(x) )# toEnum :: Type -> Int -> adef toEnum(t): '''Enumerable value from index integer''' dct = { int: int, float: float, str: chr, bool: bool } return lambda x: dct[t](x) if t in dct else t(x)# uncurry :: (a -> b -> c) -> ((a, b) -> c)def uncurry(f): '''A function over a tuple, derived from a vanilla or curried function. ''' if 1 < len(signature(f).parameters): return lambda xy: f(*xy) else: return lambda xy: f(xy[0])(xy[1])# FORMATTING -------------------------------------------------# fTable :: String -> (a -> String) -># (b -> String) -> (a -> b) -> [a] -> Stringdef fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs )# showList :: [a] -> Stringdef showList(xs): '''Stringification of a list.''' return '[' + ','.join(str(x) for x in xs) + ']'# MAIN ---if __name__ == '__main__': main()Enumeration a-z: ('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] ('α', 'ω') -> [α,β,γ,δ,ε,ζ,η,θ,ι,κ,λ,μ,ν,ξ,ο,π,ρ,ς,σ,τ,υ,φ,χ,ψ,ω] ('א', 'ת') -> [א,ב,ג,ד,ה,ו,ז,ח,ט,י,ך,כ,ל,ם,מ,ן,נ,ס,ע,ף,פ,ץ,צ,ק,ר,ש,ת] (1, 10) -> [1,2,3,4,5,6,7,8,9,10](0.61803, 5) -> [0.61803,1.61803,2.61803,3.61803,4.61803,5.61803] ('🌱', '🍂') -> [🌱,🌲,🌳,🌴,🌵,🌶,🌷,🌸,🌹,🌺,🌻,🌼,🌽,🌾,🌿,🍀,🍁,🍂]The wordconstant causes the preceding nest to be evaluated during compilation soalpha$ is a literal, not an expression computed during program evaluation.
[ [] 26 times [ i^ char a + join ] ] constant is alpha$ ( --> $ )alpha$ echo$
abcdefghijklmnopqrstuvwxyz
# From constants built into R:letters# Or generate the same with:sapply(97:122, intToUtf8)
(define lowercase-letters (build-list 26 (lambda (x) (integer->char (+ x (char->integer #\a))))))
(formerly Perl 6)
say my @letters = 'a'..'z';
'a'..'z' is a range literal, it constructs an immutableRange object.@ variable flattens it into anArray.This version only works under ASCII machines (where the values of the lowercasea through the lowercasez characters are contiguous (and consecutive).
/* REXX ---------------------------------------------------------------* 08.02.2014 Walter Pachl*--------------------------------------------------------------------*/say xrange('a','z')Output:
abcdefghijklmnopqrstuvwxyz
This REXX version shows how to generate an indexable string of a similar sequence as per the
lowercase ASCII alphabet (or rather, the Latin [English] alphabet), using a reliable style of coding
(for both ASCII and EBCDIC systems).
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 anEBCDIC system, there are 41 characters between (lowercase) a ──► z
(inclusive), some of which don't have viewable/displayable glyphs.
/*REXX program creates an indexable string of lowercase ASCII or EBCDIC characters: a─►z*/$= /*set lowercase letters list to null. */ do j=0 for 2**8; _=d2c(j) /*convert decimal J to a character. */ if datatype(_, 'L') then $=$ || _ /*Is lowercase? Then add it to $ list.*/ end /*j*/ /* [↑] add lowercase letters ──► $ */say $ /*stick a fork in it, we're all done. */
output
abcdefghijklmnopqrstuvwxyz
for i in 'a':'z' put inext
≪ "" "a" NUM "z" NUMFOR ascii ascii CHR +NEXT≫ EVAL
1: "abcdefghijklmnopqrstuvwxyz"
p ('a' .. 'z').to_ap [*'a' .. 'z']fn main() { // An iterator over the lowercase alpha's let ascii_iter = (0..26) .map(|x| (x + b'a') as char); println!("{:?}", ascii_iter.collect::<Vec<char>>());}['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']
Simpler solution:
'a'..='z'
Char_Type is just an integer-type so a "range array" can be easily created:
variable alpha_ch = ['a':'z'], a;
If you need single-char strings, convert thusly:
variable alpha_st = array_map(String_Type, &char, alpha_ch);
Let's take a peek:
print(alpha_st[23]);foreach a (alpha_ch) () = printf("%c ", a);"x"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
object Abc extends App { val lowAlpha = 'a' to 'z' //That's all // Now several tests assert(lowAlpha.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 alphabet.") assert(lowAlpha.size == 26, "No 26 characters in alphabet") assert(lowAlpha.start == 'a', "Character 'a' not first char! ???") assert(lowAlpha.head == 'a', "Character 'a' not heading! ???") assert(lowAlpha.head == lowAlpha(0), "Heading char is not first char.") assert(lowAlpha contains 'n', "Character n not present.") assert(lowAlpha.indexOf('n') == 13, "Character n not on the 14th position.") assert(lowAlpha.last == lowAlpha(25), "Expected character (z)on the last and 26th pos.") println(s"Successfully completed without errors. [within ${ scala.compat.Platform.currentTime - executionStart } ms]")}Successfully completed without errors. [within 675 ms]Process finished with exit code 0
(map integer->char (iota 26 (char->integer #\a)))
(#\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)
$ 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;
abcdefghijklmnopqrstuvwxyz
var arr = 'a'..'z';say arr.join(' ');| asciiLower |asciiLower := String new.97 to: 122 do: [:asciiCode | asciiLower := asciiLower , asciiCode asCharacter].^asciiLower
&ALPHABET ('a' LEN(25)) . OUTPUT ;* Works in ASCII but not EBCDIC.> i, 1..26 d = [i+96,0] a[i] = #.str(d)<'now A is an array of letters a..z> i, 1..#.size(a,1) #.output(a[i],#.rs)<
abcdefghijklmnopqrstuvwxyz
val lowercase_letters = List.tabulate (26, fn x => chr (x + ord #"a"));
// built-in: lowercase and uppercase lettersdisplay c(alpha)display c(ALPHA)// generate a variable with the lettersclearset obs 26gen a=char(96+_n)// or in Matamatachar(97..122)end
Previously, it was claimed that the method that maps ascii number to character is polymorphic on collections. However, that doesn't seem to be the case – at least not anymore in the newer version (3.10.2). A fix was added below the original code.
(97..122).asAscii; // This example unfortunately throws an error // for me when running it on version 3.10.2// Apparently, the message 'asAscii' cannot be understood by // an Array, so I used the message 'collect' to apply the function // enclosed in {} to each individual element of the Array, // passing them the message 'asAscii':(97..122).collect({|asciiCode| asciiCode.asAscii}); // Instead of writing the ascii codes directly as numbers, // one could also pass the chars a and z the message 'ascii' to convert // them to ascii codes – perhaps making the code a bit clearer:($a.ascii..$z.ascii).collect({|asciiCode| asciiCode.asAscii}); // both examples 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 ]Backwards:
"abcdefghijklmnopqrstuvwxyz".ascii// answers [ 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122 ]
var letters = [Character]()for i in 97...122 { let char = Character(UnicodeScalar(i)) letters.append(char)}The most common way of doing this in Tcl would be to use a simple literal; it's only 51 characters after all:
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}Though it could be done like this as well:
set alpha [apply {{} { scan "az" "%c%c" from to for {set i $from} {$i <= $to} {incr i} { lappend l [format "%c" $i] } return $l}}]+@a⇡26
"abcdefghijklmnopqrstuvwxyz"
In bash or ksh93 withbraceexpand set:
lower=({a..z})In zsh withbraceccl set:
lower=({a-z})Either way, you can display the result like this:
echo "${lower[@]}"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
Creates a string named low containing the lower case ASCII alphabet.
decl int idecl string lowfor (set i (ord "a")) (< i (+ (ord "z") 1)) (inc i) set low (+ low (chr i))end forout low endl console
module main; integer i; initial begin for(i = 97; i <= 122; i=i+1) begin $write("%c ",i); end $finish ; endendmodulea 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
let lower = []for c in range(0, 25) let lower += [nr2char(c + char2nr("a"))]endforor:
echo map(range(char2nr('a'), char2nr('z')), 'nr2char(v:val)')fn loweralpha() string { mut p := []u8{len: 26} for i in 97..123 { p[i-97] = u8(i) } return p.bytestr()}(module $lowercase (import "wasi_unstable" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)) ) (memory 1) (export "memory" (memory 0)) (func $main (export "_start") (local $i i32) (i32.store (i32.const 0) (i32.const 8)) ;; offset to start of string (i32.store (i32.const 4) (i32.const 27)) ;; string length (set_local $i (i32.const 0)) (loop ;; mem[i+8] = i+97 (i32.store (i32.add (get_local $i) (i32.const 8)) (i32.add (get_local $i) (i32.const 97))) ;; i = i+1 (set_local $i (i32.add (get_local $i) (i32.const 1))) ;; if i < 26 then loop (br_if 0 (i32.lt_s (get_local $i) (i32.const 26))) ) ;; append a newline (i32.store (i32.add (get_local $i) (i32.const 8)) (i32.const 10)) ;; write to stdout (call $fd_write (i32.const 1) ;; output stream to write to (1 == stdout) (i32.const 0) ;; memory location containing string offset and length (i32.const 1) ;; number of strings to write (i32.const 40) ;; location in memory to write number of bytes written ) drop ))
abcdefghijklmnopqrstuvwxyz
var alpha = []for (c in 97..122) alpha.add(String.fromByte(c))System.print(alpha.join())
abcdefghijklmnopqrstuvwxyz
; compile with:; nasm -f elf64 alpha.asm -o alpha.o; ld -z noexecstack -no-pie -s alpha.o -o alphaglobal _startsection .text_start: xor rax, rax .loop: mov dil, 'a' ;Our character add dil, al ;add number in rax/al mov byte[alphabet + rax], dil ;store character to memory inc rax ;increment rax cmp rax, 26 ;is rax less than 26? jl .loop ;yes? jump to .loop .print: mov byte[alphabet + rax], 0x0a ;Make the last character an lf. mov rax, 1 ;write to mov rdi, 1 ;stdout mov rsi, alphabet ;pointer to string mov rdx, 27 ;the number of characters syscall ;print it! .exit: mov rax, 60 ;exit xor rdi, rdi ;exit code zero syscallsection .bssalphabet: resb 27
$ ./alphaabcdefghijklmnopqrstuvwxyz
format ELF64 executable 3entry beginsegment executable readablebegin: mov rcx, 26 mov rdi, alphabet mov rax, 'a' .loop0: stosb inc rax loop .loop0 mov byte[alphabet + 26], 0x0a .print0: mov rax, 1 mov rdi, 1 mov rsi, alphabet mov rdx, 27 syscall .end: mov rax, 60 xor rdi, rdi syscallsegment readable writeablealphabet: rb 27
~/fasm$ fasm lower.asm lowerflat assembler version 1.73.30 (16384 kilobytes memory)3 passes, 252 bytes.~/fasm$ chmod 755 lower~/fasm$ ./lowerabcdefghijklmnopqrstuvwxyz~/fasm$
h$` h$` >0_0 t h$y ms p h? jn00_0 p r h#1 ma t jn0_0 >00_0 p p r p
(defun ascii-lower () (defun add-chars (x y s) (if (<= x y) (add-chars (+ x 1) y (string-append s (string (integer->char x)))) s)) (add-chars 97 122 ""))
char I, A(26);for I:= 0 to 26-1 do A(I):= I+^a
org &8000ld a,'a' ;datald b,26 ;loop counterld hl,Alphabet ;destinationloop:ld (hl),a ;store "a" into raminc a ;next letterinc hl ;next storage bytedjnz loop ;repeat until 26 letters were stored.call Monitor_MemDump ;hexdumps the specified address and bytecount to screen - created by Keith S. of Chibiakumasbyte 32 ;number of bytes to displayword Alphabet ;address to dump fromret ;return to basicAlphabet: ds 26,0 ;reserve 26 bytes of ram, init all to zero.
8013:61 62 63 64 65 66 67 68 abcdefgh69 6A 6B 6C 6D 6E 6F 70 ijklmnop71 72 73 74 75 76 77 78 qrstuvwx79 7A 00 00 00 00 00 00 yz
["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 constconst std = @import("std");pub fn main() !void { const cnt_lower = 26; var lower: [cnt_lower]u8 = undefined; comptime var i = 0; inline while (i < cnt_lower) : (i += 1) lower[i] = i + 'a'; const stdout_wr = std.io.getStdOut().writer(); for (lower) |l| try stdout_wr.print("{c} ", .{l}); try stdout_wr.writeByte('\n');}