From 6e3966418ffc932bbea41cd4711d65188e7c7fb6 Mon Sep 17 00:00:00 2001 From: gwen Date: Thu, 13 Apr 2017 17:36:25 +0200 Subject: [PATCH] =?UTF-8?q?port=C3=A9e=20d'une=20variable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- algorithmique/cours/fonctions.txt | 76 ++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/algorithmique/cours/fonctions.txt b/algorithmique/cours/fonctions.txt index 4e71600..a637574 100644 --- a/algorithmique/cours/fonctions.txt +++ b/algorithmique/cours/fonctions.txt @@ -107,8 +107,10 @@ Environnement Portée - La portée d'une variable est sa condition d'utilisation dans un contexte donné + La portée d'un identifiant (une variable) est sa condition d'utilisation dans un contexte donné (utilisation locale uniquement, ou bien globale, ou bien locale et globale) + La portée d’une liaison est la portion du code dans laquelle cette + liaison est valide (i.e. où un identifiant est lié à une expression). .. ifconfig:: exercice @@ -127,6 +129,78 @@ Portée - : int = 1 + +.. code-block:: ocaml + + let a = 3 (* première liaison pour l'identifiant a *) + let b = 5 and c = 6 + let somme = a + b + c + val somme : int = 14 + let a = 45 (* deuxième liaison pour l'identifiant a *) + somme + val a : int = 45 + +.. ifconfig:: exercice + + **Exercice** : Que donne ce code ? + + .. code-block:: ocaml + + let a = 3 and b = 4 and c = 8 ;; + let somme = a + b + c ;; + val somme : int = ??? + let a = 44 + let b = 5 + let c = 1 + somme + - : int = ??? + +.. ifconfig:: correction + + .. code-block:: ocaml + + let a = 3 and b = 4 and c = 8 ;; + - : int = 15 + let somme = a + b + c ;; + val somme : int = 15 + let a = 44 + let b = 5 + let c = 1 + somme + - : int = 15 + + Même code en python + + .. code-block:: python + + >>> a = 1 + >>> b = 2 + >>> c = 3 + >>> somme = a + b + c + >>> somme + 6 + >>> a = 56 + >>> b = 5678 + >>> c = 56789 + >>> somme + 6 + >>> + +Portée locale dans une expression + +.. code-block:: ocaml + + # let a = 2 and b = 3 and c = 4 in + let somme = a+b+c in + somme + - : int = 9 + # somme ;; + Error: Unbound value somme + # a ;; + Error: Unbound value a + + + Exemple de variable globale modifiée localement (** attention, mauvaise pratique ** !) : .. code-block:: python