Nested case statements in SML - coding-style

This is more of a stylistic question than anything else. Given the following piece of code:
case e1 of (* datatype type_of_e1 = p1 | p2 *)
p1 => case e11 of (* datatype type_of_e11 = NONE | SOME int *)
NONE => expr11
| SOME v => expr12 v
| p2 => case e21 of (* datatype type_of_e21 = NONE | SOME string *)
NONE => expr21
| SOME v => expr22 v
Is there a way to resolve the types of rules don't agree error caused by trying to pattern match e11 to p2, other than enclosing p1's expression in parenthesis? The p2 pattern has another case statement, to avoid the 'just switch the patterns' answer ;-).
update: changed the code to reflect a more concrete case

The answer is "(" and ")". My example:
case e1 of
p1 => ( case e11 of
NONE => expr11
| SOME v => expr12 v )
| p2 => ( case e21 of
NONE => expr21
| SOME v => expr22 v )
This really works! Cool :) You can try it too.

No. The syntactic rules in the Definition of Standard ML state that the match arms of a case expression attempt to maximally consume potential clauses. And since there's no "end case" or similar marker in the language, the parser will merrily eat each of the "| pat => exp" clauses that you feed it until it sees something that terminates a list of match clauses.

Plain and short answer: no. But what's wrong with parentheses?
(Of course, you can also bracket in other ways, e.g. with a 'let', or by factoring into auxiliary functions, but parentheses are the canonical solution.)

Related

"=>" symbol definition in Picat

What is the definition of the symbol "=>" in Picat and how do you read it ? Is it an implication ? I have trouble to understand it since there seems to be no informations about it in the manual nor in the book.
%example using "=>"
main =>
A = true,
B = true,
C = function(A,B),
predicate(A,B).
function(true,true) = R => R = true.
predicate(true,true) => true.
How would you describe the meaning of "=>" in the previous example ? Is it just something syntactically required, such as "{" after the declaration of a method in Java, or has a deeper meaning ?
Briefly, if you use => instead of :-, you are essentially writing a deterministic predicate. As we know that Prolog is a practical programming language and it is not necessary to keep all predicates pure. A lot of time, we actually write impure programs by cut and hope single sided unification. The => just provides a convenient mechanism to write such programs.
You can understand => by program transformation.
p(A1,A2,...An), C1, C2, ... => Body
is semantically equivalent to
p(V1,V2,...Vn) :-
Pattern = p(A1,A2,...An),
Args = p(V1,V2,...Vn),
subsumes_term(Pattern, Args),
Pattern = Args,
C1, C2, ...,
!,
Body.
More detail see https://swi-prolog.discourse.group/t/picat-style-matching

Proof arguments in Coq

I'm trying to define a function on a weakly-specified type in Coq. Specifically, I have a type that is defined inductively by a set of recursive constructors, and I want to define a function that is only defined when the argument has been constructed using a subset of these.
To be more concrete, I have the following type definition:
Inductive Example : Set :=
| Example_cons0 : nat -> Example
| Example_cons1 : Example -> Example
.
Now, I have a function that only applies to the ground case. (The following definition will not work obviously, but is meant to suggest my intent.)
Definition example (x:Example) : nat :=
match x with
| Example_cons0 n => n
end.
Ideally, I'd like to communicate that my argument, x, has been constructed using a subset of the general type constructors, in this case, Example_cons0. I thought that I could do this by defining a predicate that states this fact and passing a proof of the predicate as an argument. For example:
Definition example_pred (x:Example) : Prop :=
match x with
| Example_cons0 _ => True
| _ => False
end.
And then (following the recommendation given by Robin Green) something like,
Definition example2 (x:Example) : example_pred x -> nat :=
(use proof to define example2?)
Unfortunately, I'm not sure how I would go about doing any of this. I'm not even sure that this is the correct way to define restricted functions on weakly-specified types.
Any guidance, hints, or suggestions would be strongly appreciated!
- Lee
Update:
Following recommendations by jozefg, the example function can be defined as:
Definition example (x:Example) : example_pred x -> nat :=
match x with
| Example_cons0 n => fun _ => n
| _ => fun proof => match proof with end
end.
See his comments for details. This function can be evaluated using the following syntax, which also demonstrates how proof terms are represented in Coq:
Coq < Eval compute in Example.example (Example.Example_cons0 0) (I : Example.example_pred (Example.Example_cons0 0)).
= 0
: nat
Here's how I'd write this as a simplified example
Consider a simple data type
Inductive Foo :=
| Bar : nat -> Foo
| Baz.
And now we define a helpful function
Definition bar f :=
match f with
| Bar _ => True
| Baz => False
end.
And finally what you want to write:
Definition example f :=
match f return bar f -> nat with
| Bar n => fun _ => n
| Baz => fun p => match p with end
end.
This has the type forall f : Foo, bar f -> nat. This works by making sure that in the case that example was not supplied a Bar, that the user must supply a proof of false (impossible).
This can be called like this
example (Bar n) I
But the problem is, you may have to manually prove some term is constructed by Bar, otherwise how is Coq supposed to know?
Yes, you are on the right lines. You want:
Definition example2 (x:Example) (example_pred x) : nat :=
and how to proceed further would depend on what you wanted to prove.
You might find it helpful to make a definition by proving with tactics, using the Curry-Howard correspondence:
Definition example2 (x:Example) (example_pred x) : nat.
Proof.
some proof
Defined.
Also, I'd like to point out that the sig and sigT types are often used to combine "weakly-specified types" with predicates to constrain them.

F# explicit match vs function syntax

Sorry about the vague title, but part of this question is what these two syntax styles are called:
let foo1 x =
match x with
| 1 -> "one"
| _ -> "not one"
let foo2 = function
| 1 -> "one"
| _ -> "not one"
The other part is what difference there is between the two, and when I would want to use one or the other?
The pro for the second syntax is that when used in a lambda, it could be a bit more terse and readable.
List.map (fun x -> match x with | 1 -> "one" | _ -> "not one") [0;1;2;3;1]
vs
List.map (function 1 -> "one" | _ -> "not one") [0;1;2;3;1]
The match version is called a "pattern matching expression". The function version is called a "pattern matching function". Found in section 6.6.4 of the spec.
Using one over the other is a matter of style. I prefer only using the function version when I need to define a function that is only a match statement.
The function version is a short hand for the full match syntax in the special case where the match statement is the entire function and the function only has a single argument (tuples count as one). If you want to have two arguments then you need to use the full match syntax*. You can see this in the types of the following two functions.
//val match_test : string -> string -> string
let match_test x y = match x, y with
| "A", _ -> "Hello A"
| _, "B" -> "Hello B"
| _ -> "Hello ??"
//val function_test : string * string -> string
let function_test = function
| "A", _ -> "Hello A"
| _, "B" -> "Hello B"
| _ -> "Hello ??"
As you can see match version takes two separate arguments whereas the function version takes a single tupled argument. I use the function version for most single argument functions since I find the function syntax looks cleaner.
*If you really wanted to you can get the function version to have the right type signature but it looks pretty ugly in my opinion - see example below.
//val function_match_equivalent : string -> string -> string
let function_match_equivalent x y = (x, y) |> function
| "A", _ -> "Hello A"
| _, "B" -> "Hello B"
| _ -> "Hello ??"
They do the same thing in your case -- the function keyword acts like a combination of the fun keyword (to produce an anonymous lambda) followed by the match keyword.
So technically these two are the same, with the addition of a fun:
let foo1 = fun x ->
match x with
| 1 -> "one"
| _ -> "not one"
let foo2 = function
| 1 -> "one"
| _ -> "not one"
Just for completeness sake, I just got to page 321 of Expert FSharp:
"Note, Listing 12-2 uses the expression form function pattern-rules -> expression. This is equivalent to (fun x -> match x with pattern-rules -> expression) and is especially convenient as a way to define functions working directly over discriminated unions."
function only allows for one argument but allows for pattern matching, while fun is the more general and flexible way to define a function. Take a look here: http://caml.inria.fr/pub/docs/manual-ocaml/expr.html
The two syntaxes are equivalent. Most programmers choose one or the other and then use it consistently.
The first syntax remains more readable when the function accepts several arguments before starting to work.
This is an old question but I will throw my $0.02.
In general I like better the match version since I come from the Python world where "explicit is better than implicit."
Of course if type information on the parameter is needed the function version cannot be used.
OTOH I like the argument made by Stringer so I will start to use function in simple lambdas.

Does "match ... true -> foo | false -> bar" have special meaning in Ocaml?

I encountered the following construct in various places throughout Ocaml project I'm reading the code of.
match something with
true -> foo
| false -> bar
At first glance, it works like usual if statement. At second glance, it.. works like usual if statement! At third glance, I decided to ask at SO. Does this construct have special meaning or a subtle difference from if statement that matters in peculiar cases?
Yep, it's an if statement.
Often match cases are more common in OCaml code than if, so it may be used for uniformity.
I don't agree with the previous answer, it DOES the work of an if statement but it's more flexible than that.
"pattern matching is a switch statement but 10 times more powerful" someone stated
take a look at this tutorial explaining ways to use pattern matching Link here
Also, when using OCAML pattern matching is the way to allow you break composed data to simple ones, for example a list, tuple and much more
> Let imply v =
match v with
| True, x -> x
| False, _ -> true;;
> Let head = function
| [] -> 42
| H:: _ -> am;
> Let rec sum = function
| [] -> 0
| H:: l -> h + sum l;;

MGrammar for parsing IF statement

I am building up a MGrammar spec to parse some pseudo code looking for particular bits of information. I have most of the spec working except for 1 cruical element.
The pseudo code supports an if-then-else syntax and I have been unable to find a satisfactory way of parsing it. The exact construct is...
IF expression operator expression THEN
Statement1
Statement2
Statementn
ELSEIF expression operator expression THEN
Statement1
Statement2
Statementn
ELSE
Statement1
Statement2
Statementn
ENDIF
...Where the Else and Elseif are optional.
What I have so far is:
`syntax Statement = r:ReturnClause => r |
i:IfClause => i |
ei:ElseifClause => ei |
e:ElseClause => e |
end:EndClause => end |
v:Expression => v ;
syntax IfClause = If name:Identifier operator:Operator Then statement:Statement => If[name, operator, Then[statement]];
syntax ElseifClause = Elseif name:Identifier operator:Operator Then statement:Statement => ElseIf[name, operator, Then[statement]];
syntax ElseClause = Else statement:Statement => Else[statement];
syntax EndClause = Endif; `
However, the Statement after the 'Then' and 'Else' is not greedy enough and only captures the first statement in the parse tree.
Has anyone tried to implement the parsing of an If statement using MGrammar or have any suggestions??
You can find a (almost) complete C# 4.0 grammar in the archetype project on codeplex. Dan Vanderboom wrote it in preparation of his new language code named "Archetype".
Maybe that helps: http://archetype.codeplex.com/

Resources