Ci sono due cose diverse che accadono qui. Il primo esempio utilizza l'operatore (:)
per creare un nuovo elenco dall'elemento 1
e dall'elenco [2,3]
.
1:[2,3]
tuo secondo esempio utilizza pattern matching. L'espressione ...
myInt (x:xs) = ...
... essenzialmente dice "se l'argomento di myInt
costituito da un elemento preposto ad una lista (eventualmente vuoto), quindi Chiamiamo il primo elemento x
e l'elenco xs
". Questo esempio può essere più chiaro:
λ> let { myInt :: [Int] -> String ; myInt (x:xs) = "The first element is " ++ show x ++ " and the rest of the list is " ++ show xs}
λ> myInt [1,2,3]
"The first element is 1 and the rest of the list is [2,3]"
Si noti che questo funzionerà solo se l'elenco di input contiene almeno un elemento.
λ> myInt []
"*** Exception: <interactive>:9:34-127: Non-exhaustive patterns in function myInt
Possiamo comunque gestire il caso in cui la lista di input è vuota simili:
λ> let { myInt :: [Int] -> String ; myInt (x:xs) = "The first element is " ++ show x ++ " and the rest of the list is " ++ show xs; myInt _ = "empty list"}
λ> myInt []
"empty list"
E 'bello ricordare che haskell98 consente * costruttori di infisso * tipo, che deve iniziare con "': '", quindi la lista cons costruttore (che prende due argomenti) è un caso un po' particolare di questa regola generale. – jberryman