Definir funciones en Haskell
Una cotización de envío armada con dos funciones chicas y un patrón literal.
-- A function is an equation: name, arguments by juxtaposition, body.
boxFee :: Double -> Double -> Double
boxFee weightKg ratePerKg = 3.5 + weightKg * ratePerKg
-- Two clauses tried top to bottom: the literal 0 first, then any n.
discountFor :: Int -> Double
discountFor 0 = 0.0
discountFor n = min 0.25 (fromIntegral n * 0.05)
totalCost :: Double -> Double -> Int -> Double
totalCost weightKg ratePerKg boxes =
boxFee weightKg ratePerKg * (1 - discountFor boxes)
main :: IO ()
main = print (totalCost 2.5 1.8 3)
Cómo funciona
boxFee weightKg ratePerKgrecibe sus dos argumentos escritos uno al lado del otro.discountFor 0es una ecuación aparte dediscountFor ny se prueba primero.totalCostllama a las dos, ymainimprimetotalCost 2.5 1.8 3.
Palabras clave y builtins usados aquí
DoubleIOInt
El intento, en números
- Líneas
- 15
- Caracteres a escribir
- 516
- Tokens
- 75
- Ritmo de tres estrellas
- 80 tpm
Al ritmo de tres estrellas de 80 tokens por minuto, este intento toma unos 56 segundos.
Paso 1 de 3 en Funciones; paso 4 de 27 en Fundamentos del lenguaje.