What doesx :: xs' mean?
I dont have much functional experience but IIRC in F# 1 :: 2 :: 3 :: [];; creates an array of [1,2,3]
so what does the ‘ do?
let rec sum xs =
match xs with
| [] -> 0
| x :: xs' -> x + sum xs'
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think sepp2k already answered most of the question, but I’d like to add a couple of points that may clarify how F#/OCaml compiler interprets the code and explain some common uses.
Regarding the
'symbol – this is just a part of a name (a valid identifier starts with a letter and then contains one or more letters, numbers or'symbols). It is usually used if you have a function or value that is very similar to some other, but is in some way new or modified.In your example,
xsis a list that should be summed and the pattern matching decomposes the list and gives you a new list (without the first element) that you need to sum, so it is calledxs'Another frequent use is when declaring a local utility function that implements the functionality and takes an additional parameter (typically, when writing tail-recursive code):
However, I think there is usually a better name for the function/value, so I try to avoid using
'when writing code (I think it isn’t particularly readable and moreover, it doesn’t colorize correctly on StackOverflow!)Regarding the
::symbol – as already mentioned, it is used to create lists from a single element and a list (1::[2;3]creates a list[1;2;3]). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.When creating a list, you use it as an operator that constructs a list (just like when you use
+to add two numbers). However, when you use it in thematchconstruct, it is used as a pattern, which is a different syntactic category – the pattern is used to decompose the list into an element and the remainder and it succeeds for any non-empty list: