I expected these definitions of a function getting the second element in a list to be the same
let myFunction (a:(b:_)) = b
let myFunction [a,b,_] = b
... but the second one doesn't work for infinite lists
Prelude> let myFunction [a,b,_] = b
Prelude> myFunction [1..]
*** Exception: <interactive>:8:5-26: Non-exhaustive patterns in function myFunction
What's the difference?
Edit: maybe [a,b,_] expands to (a:(b:(_:[])))?
[x,_] only matches a list with exactly two elements. Likewise, [a,b,_] matches any list with exactly three elements, putting the first element in a, the second element in b and discarding the third. (x:_), on the other hand, matches any list with at least one element, putting the first element in x and discarding the rest.
(:) is the list constructor. All non-empty lists are composed of calls to (:). Note that [a,b,c] is syntactic sugar for a : (b : (c : [])).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With