Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with [x,_] syntax vs (x:_) for infinite lists in haskell

Tags:

haskell

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:(_:[])))?

like image 354
user3125280 Avatar asked Dec 26 '22 05:12

user3125280


1 Answers

[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 : [])).

like image 184
David Young Avatar answered May 23 '23 05:05

David Young