projprog/HSK15.md

2.0 KiB

Haskell 15

Exercice 1

myMean :: Fractional a => Real a => a -> a -> String
myMean x y
    | (x+y)/2>12 = "You are a good student"
    | (x+y)/2>=10 = "You can be do what you want to do"
    | otherwise = "You are a bad student"
  1. Le mot-clé where sert en Haskell à définir des variables temporaires afin d'éviter de réutiliser une expression à plusieurs emplacement du code. Cela permet d'assure que le calcul n'est effectué qu'une seule fois.
myMean2 :: Fractional a => Real a => a -> a -> String
myMean2 x y
    | moy>12 = "You are a good student"
    | moy>=10 = "You can be do what you want to do"
    | otherwise = "You are a bad student"
    where moy=(x+y)/2

L'intéret est que les variables on plus de sens (car elles ont maintenant un nom) que des formules. 4.

myMean3 :: Fractional a => Real a => a -> a -> String
myMean3 x y
    | moy>=acceptable = "You are a good student"
    | moy>=pass = "You can be do what you want to do"
    | otherwise = "You are a bad student"
    where 
    moy=(x+y)/2
    pass=10
    acceptable=12

Exercice 2

  1. Il est tout à fait possible d'utiliser le pattern matching dans un where.
myMean4 :: Fractional a => Real a => a -> a -> String
myMean4 x y
    | moy>=acceptable = "You are a good student"
    | moy>=pass = "You can be do what you want to do"
    | otherwise = "You are a bad student"
    where (moy,pass,acceptable)=((x+y)/2,10,12)
whereList :: Show a => Show b => [a] -> [b] -> String
whereList l1 l2
    | length l1 > 1 && length l2 > 1 = show secondl1 ++ " " ++ show lastl2
    | length l1 <= 1  && length l2 <= 1 = "The lengths of l1 and l2 are too short"
    | length l1 <= 1 = "The length of l1 is too short"
    | length l2 <= 1 = "The length of l2 is too short"
    where 
    _:secondl1:_ = l1
    lastl2 = last l2

Exercice 3

  1. Il est tout à fait possible de définir des fonctions dans un where.
listMean :: [(Double,Double)] -> [Double]
listMean l = [moy x y | (x,y) <- l]
    where moy u v = (u+v)/2