Rappel sur le cours précédent

Conception de fonctions sur les énumérations et unions

https://htdp.org/2018-01-06/Book/part_one.html#%28part._sec~3adesign-itemization%29

Énumérations:

; A TrafficLight is one of the following Strings:
; – "red"
; – "green"
; – "yellow"
; interpretation: the three strings represent the three 
; possible states that a traffic light may assume 

; TrafficLight -> TrafficLight
; yields the next state given current state s

Unions:

; An NorF is one of: 
; – a Number
; – #false

; negate: NorF -> NorF

Conception de types récursifs

https://htdp.org/2018-01-06/Book/part_two.html#%28part._ch~3adesign-lists%29

Un ou plusieurs cas de base, un ou plusieurs cas récursifs.

; a List-of-names is one of: 
; – '()
; – (cons String List-of-names)
; interpretation: a list of students, by first name

Autre exemple :

; a ChoiceGame is one of:
; - Bool: a result
; - (make-choice String ChoiceGame ChoiceGame): a choice

; - question: String
; - yes: ChoiceGame, what to do if the answer is "yes"
; - no: ChoiceGame, what to do if the anser is "no"
(define-struct choice [question yes no])

Dans les cas récursifs, on fait des appels récursifs.

(define (shortest-play game)
  (cond
    [(boolean? game) 0]
    [(choice? game)
     (+ 1
        (min (shortest-play (choice-yes game))
             (shortest-play (choice-no game))))]))


(define (number-of-plays g)
  (cond
    [(boolean? g) 1]
    [(choice? g)
     (+ (number-of-plays (choice-yes g))
        (number-of-plays (choice-no g)))]))

Exercices (sur feuille): longest-play, number-of-plays.

; number-of-plays: Game -> Number ; return the number of different plays possible on a game (check-expect (number-of-plays #true) 1) (define jeu (make-choice "Rapide ou lent ?" #false (make-choice "Oui ?" #true #false))) (check-expect (number-of-plays jeu) 3)

Exercices

Exercices

'() (cons x xs) (empty? list) (first list) (rest list)

; sum : list-of-Numbers -> Number
; list-length : list-of-Any -> Number
; average : list-of-Numbers -> Number

; concat: List-of-Strings -> String
; concatenates all strings in l into one long string

Récursivité terminale

(hors livre, raccord avec les autres cours)

 ; sum : list-of-Numbers -> Number
 ; list-length : list-of-Any -> Number
 ; average : list-of-Numbers -> Number

 ; sum-with-acc : list-of-Numbers Number -> Number
 ; list-length-with-acc : list-of-Any Number -> Number

Cours

Récursion sur les nombres naturels

Exercice:

; copier: Number -> String -> List String
(check-expect (copier 2 "fou") (cons "fou" (cons "fou" '())))

Exercices:

(require 2htdp/image)
(define img (square 10 "solid" "red"))

; col: Number -> Image -> Image
(check-expect (col 2 img) (above img img)) 

; row: Number -> Image -> Image
(check-expect (row 2 img) (beside img img))