Questo codice:Haskell "where" indentation: perché deve essere indentato l'identificatore passato?
import Data.Char (digitToInt)
myInt :: String -> Int
myInt [] = error "bad input: empty string"
myInt (x:xs)
| x == '-' = -1 * myInt xs
| otherwise = foldl convert 0 (x:xs)
where convert acc x
| x `elem` ['0'..'9'] = 10 * acc + digitToInt x
| otherwise = error ("bad input: not an int - " ++ [x])
non riesce:
Prelude> :l safeListFs.hs
[1 of 1] Compiling Main (safeListFs.hs, interpreted)
safeListFs.hs:9:8: parse error (possibly incorrect indentation)
Failed, modules loaded: none.
Ma questa versione:
import Data.Char (digitToInt)
myInt :: String -> Int
myInt [] = error "bad input: empty string"
myInt (x:xs)
| x == '-' = -1 * myInt xs
| otherwise = foldl convert 0 (x:xs)
where convert acc x
| x `elem` ['0'..'9'] = 10 * acc + digitToInt x
| otherwise = error ("bad input: not an int - " ++ [x])
è ok:
Prelude> :l safeListFs.hs
[1 of 1] Compiling Main (safeListFs.hs, interpreted)
Ok, modules loaded: Main.
non riesco a capire il motivo per cui quelli due ultimi a le ammaccature contano.
Questa domanda è un buon esempio del perché io odio la sintassi spazi di Haskell; mi sembra sempre non intuitivo rispetto a, diciamo, Python. Sfortunatamente, l'unica cosa che non mi piace di più è brutta parentesi graffe che sporca il mio codice. –
http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html#deftypes.offside La regola del fuorigioco mi sembra intuitiva. Devi solo smettere di pensare ai blocchi (come Python, che non ha senso in Haskell) e pensare invece alle continuazioni di una dichiarazione o espressione. – ephemient
Utilizza un editor di testo intelligente e dimentica le strane regole di identificazione. –