ten kod:Haskell "gdzie" wcięcie: dlaczego musi być wcięty w przeszłości identyfikator?
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])
zawodzi:
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.
Ale ta wersja:
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])
jest ok:
Prelude> :l safeListFs.hs
[1 of 1] Compiling Main (safeListFs.hs, interpreted)
Ok, modules loaded: Main.
Nie mogę zrozumieć, dlaczego te dwa ostatnie w wgniecenia mają znaczenie.
to pytanie jest dobrym przykładem tego, dlaczego nienawidzę składnia spacje Haskell'a; zawsze wydaje mi się to nieintuicyjne w porównaniu do, powiedzmy, Pythona. Niestety, jedyną rzeczą, której nie lubię * więcej *, są brzydkie nawiasy klamrowe zaśmiecające mój kod. –
http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html#deftypes.offside Zasada "offside" wydaje mi się intuicyjna. Trzeba po prostu przestać myśleć o blokach (jak Python, co nie ma sensu w Haskell) i zamiast tego myśleć o kontynuacji deklaracji lub wyrażenia. – ephemient
Użyj sprytnego edytora tekstu i zapomnij o dziwnych regułach identyfikacji. –