[Haskell-beginners] Understanding types and constructors more thoroughly
Josh Diamond
evildude at live.co.uk
Thu May 21 10:45:50 UTC 2020
Ok so I have an assessment, first part is:
Consider the following declaration for a parameterised type of lists in which
Nil represents the empty list, and Cons x xs represent a non-empty list with
first element x and remaining list of elements xs:
data List a = Nil | Cons a (List a)
Am I right in reading it like: Declare a List type which can take any parameter and is constructed by Nil or Cons which itself takes anything and a List of anything?
Also it seems strange to define a List without [] or : like in the prelude but I assume it’s just for the purposes of the question. Is the (List a) used just to make the order of evaluation explicit or is it some weird thing with tuples?
Ok so the actual question is:
Q) Define a recursive function append :: List a -> List a -> List a that
appends two lists together to give a single list.
So I’d have to do something similar to how append is done in the standard prelude I.e.
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
How do I do pattern matching on a user defined type?
I was thinking something like:
Nil append List a = List a
For the first line but the second line is confusing me. I’ve read some stuff on pattern matching for data constructors but I don’t know how relevant it is here.
Maybe something like this would work:
Cons a (List a) append List b = a : (List a append List b)
But I’m getting ‘Data constructor not in scope’ for everything to do with List...it thinks it’s a data constructor although I’ve defined it as a type above.
Any help would be great 😊
Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10
Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20200521/d625cf54/attachment.html>
More information about the Beginners
mailing list