Adloun

Lexer complet

Exercice · OCaml (option informatique), chapitre 21 — Analyse syntaxique et interprétation

Énoncé

Écrire lexer gérant les nombres à plusieurs chiffres et les espaces.

Corrigé

let lexer s =
  let n = String.length s in
  let lex = ref [] and i = ref 0 in
  while !i < n do
    let c = s.[!i] in
    if c = ' ' then i := !i + 1
    else if c = '+' then begin lex := Plus :: !lex; i := !i + 1 end
    else if c = '-' then begin lex := Moins :: !lex; i := !i + 1 end
    else if c = '*' then begin lex := Fois :: !lex; i := !i + 1 end
    else if c = '(' then begin lex := ParenG :: !lex; i := !i + 1 end
    else if c = ')' then begin lex := ParenD :: !lex; i := !i + 1 end
    else if c >= '0' && c <= '9' then begin
      let v = ref 0 in
      while !i < n && s.[!i] >= '0' && s.[!i] <= '9' do
        v := !v * 10 + (int_of_char s.[!i] - int_of_char '0');
        i := !i + 1
      done;
      lex := Nombre !v :: !lex
    end
    else failwith "caractere inattendu"
  done;
  renverse !lex

La boucle interne accumule un nombre tant qu'on lit des chiffres (v := !v * 10 + chiffre). On accumule les lexèmes à l'envers, d'où le renverse final.

Les autres exercices de ce chapitre Le cours du chapitre

Un blocage sur cet exercice ? Le tuteur d'Adloun guide par questions, sans donner la réponse.