How to distinguish definition list from ordered list in rst when the term starts with number in ordinal form? - restructuredtext

Example:
1. inflection
foo
2. inflection
qux
In rst renders as ordered list but in my case it would be more fitting to use definition list.
If I remove one spaces from the definition indent to make it look like a definition like
1. inflection
foo
then rst2html emits warning of improperly ended ordered list.
If on the other hand I add indent like
1. inflection
foo
I do get a definition list but always a separate dl inside each of the ordered list item.
Context: some languages inflect nouns and I want to give a list of inflections on an unusual noun. The inflections are commonly referred to as "1. inflection, 2. inflection" etc, hence my issue to express this in rst.
My workaround so far is to avoid the numbers by using latin name of the inflections but I'd rather not to.

d'oh, Escaping mechanism works. example::
\1. inflection
foo

Related

How to define a recursive function in Isabelle/HOL?

As shown in the figure, this is a code example that defines the data types and fun functions of the source and target models in the model transformation. The first three figures correspond to the source model architecture, target model architecture, and the transformation relationship between them.
The meaning of the recursive function of the last three pictures:
The function Part1 defined in Figure 4 is based on several recursive functions.(such as getPlaces, etc.)
The function Part2 defined in Figure 5 is based on several recursive functions. (such as getTranStep2, etc.)
Figure 6 is the above basic recursive function getPlaces, which describes the parameters of the Allstate list (including final state, simple state, composite state) in the receiving source model SMD, and returns places, but does not consider the SMD initial state.
I don’t understand the expression of the recursive function in the last three pictures, especially the characters of the link expression (' ' ' ', [ ], #, #, LL, st, substs), which prevents me from understanding how the recursive function expresses the meaning.
In fact, I just want to define my source model and target model. (for example, three elements on the left correspond to one element on the right; one element on the left corresponds to two elements on the right)
Well, # is just list concatenation, x # xs is the list with head x and remaining list xs, '''' is the empty string, e.g., ''hello'' would be the string "hello" and note that strings are nothing else than lists of characters. And ll and st are just variables.
If you have problems understanding these basic parts, I suggest to first read some general introduction to Isabelle, e.g., by starting isabelle doc prog-prove or by reading the book "Concrete Semantics".

Perl 6 calculate the average of an int array at once using reduce

I'm trying to calculate the average of an integer array using the reduce function in one step. I can't do this:
say (reduce {($^a + $^b)}, <1 2 3>) / <1 2 3>.elems;
because it calculates the average in 2 separate pieces.
I need to do it like:
say reduce {($^a + $^b) / .elems}, <1 2 3>;
but it doesn't work of course.
How to do it in one step? (Using map or some other function is welcomed.)
TL;DR This answer starts with an idiomatic way to write equivalent code before discussing P6 flavored "tacit" programming and increasing brevity. I've also added "bonus" footnotes about the hyperoperation Håkon++ used in their first comment on your question.5
Perhaps not what you want, but an initial idiomatic solution
We'll start with a simple solution.1
P6 has built in routines2 that do what you're asking. Here's a way to do it using built in subs:
say { sum($_) / elems($_) }(<1 2 3>); # 2
And here it is using corresponding3 methods:
say { .sum / .elems }(<1 2 3>); # 2
What about "functional programming"?
First, let's replace .sum with an explicit reduction:
.reduce(&[+]) / .elems
When & is used at the start of an expression in P6 you know the expression refers to a Callable as a first class citizen.
A longhand way to refer to the infix + operator as a function value is &infix:<+>. The shorthand way is &[+].
As you clearly know, the reduce routine takes a binary operation as an argument and applies it to a list of values. In method form (invocant.reduce) the "invocant" is the list.
The above code calls two methods -- .reduce and .elems -- that have no explicit invocant. This is a form of "tacit" programming; methods written this way implicitly (or "tacitly") use $_ (aka "the topic" or simply "it") as their invocant.
Topicalizing (explicitly establishing what "it" is)
given binds a single value to $_ (aka "it") for a single statement or block.
(That's all given does. Many other keywords also topicalize but do something else too. For example, for binds a series of values to $_, not just one.)
Thus you could write:
say .reduce(&[+]) / .elems given <1 2 3>; # 2
Or:
$_ = <1 2 3>;
say .reduce(&[+]) / .elems; # 2
But given that your focus is FP, there's another way that you should know.
Blocks of code and "it"
First, wrap the code in a block:
{ .reduce(&[+]) / .elems }
The above is a Block, and thus a lambda. Lambdas without a signature get a default signature that accepts one optional argument.
Now we could again use given, for example:
say do { .reduce(&[+]) / .elems } given <1 2 3>; # 2
But we can also just use ordinary function call syntax:
say { .reduce(&[+]) / .elems }(<1 2 3>)
Because a postfix (...) calls the Callable on its left, and because in the above case one argument is passed in the parens to a block that expects one argument, the net result is the same as the do4 and the given in the prior line of code.
Brevity with built ins
Here's another way to write it:
<1 2 3>.&{.sum/.elems}.say; #2
This calls a block as if it were a method. Imo that's still eminently readable, especially if you know P6 basics.
Or you can start to get silly:
<1 2 3>.&{.sum/$_}.say; #2
This is still readable if you know P6. The / is a numeric (division) operator. Numeric operators coerce their operands to be numeric. In the above $_ is bound to <1 2 3> which is a list. And in Perls, a collection in numeric context is its number of elements.
Changing P6 to suit you
So far I've stuck with standard P6.
You can of course write subs or methods and name them using any Unicode letters. If you want single letter aliases for sum and elems then go ahead:
my (&s, &e) = &sum, &elems;
But you can also extend or change the language as you see fit. For example, you can create user defined operators:
#| LHS ⊛ RHS.
#| LHS is an arbitrary list of input values.
#| RHS is a list of reducer function, then functions to be reduced.
sub infix:<⊛> (#lhs, *#rhs (&reducer, *#fns where *.all ~~ Callable)) {
reduce &reducer, #fns».(#lhs)
}
say <1 2 3> ⊛ (&[/], &sum, &elems); # 2
I won't bother to explain this for now. (Feel free to ask questions in the comments.) My point is simply to highlight that you can introduce arbitrary (prefix, infix, circumfix, etc.) operators.
And if custom operators aren't enough you can change any of the rest of the syntax. cf "braid".
Footnotes
1 This is how I would normally write code to do the computation asked for in the question. #timotimo++'s comment nudged me to alter my presentation to start with that, and only then shift gears to focus on a more FPish solution.
2 In P6 all built in functions are referred to by the generic term "routine" and are instances of a sub-class of Routine -- typically a Sub or Method.
3 Not all built in sub routines have correspondingly named method routines. And vice-versa. Conversely, sometimes there are correspondingly named routines but they don't work exactly the same way (with the most common difference being whether or not the first argument to the sub is the same as the "invocant" in the method form.) In addition, you can call a subroutine as if it were a method using the syntax .&foo for a named Sub or .&{ ... } for an anonymous Block, or call a method foo in a way that looks rather like a subroutine call using the syntax foo invocant: or foo invocant: arg2, arg3 if it has arguments beyond the invocant.
4 If a block is used where it should obviously be invoked then it is. If it's not invoked then you can use an explicit do statement prefix to invoke it.
5 Håkon's first comment on your question used "hyperoperation". With just one easy to recognize and remember "metaop" (for unary operations) or a pair of them (for binary operations), hyperoperations distribute an operation to all the "leaves"6 of a data structure (for an unary) or create a new one based on pairing up the "leaves" of a pair of data structures (for binary operations). NB. Hyperoperations are done in parallel7.
6 What is a "leaf" for a hyperoperation is determined by a combination of the operation being applied (see the is nodal trait) and whether a particular element is Iterable.
7 Hyperoperation is applied in parallel, at least semantically. Hyperoperation assumes8 that the operations on the "leaves" have no mutually interfering side-effects -- that is to say, that any side effect when applying the operation to one "leaf" can safely be ignored in respect to applying the operation to any another "leaf".
8 By using a hyperoperation the developer is declaring that the assumption of no meaningful side-effects is correct. The compiler will act on the basis it is, but will not check that it is true. In the safety sense it's like a loop with a condition. The compiler will follow the dev's instructions, even if the result is an infinite loop.
Here is an example using given and the reduction meta operator:
given <1 2 3> { say ([+] $_)/$_.elems } ;

Number of valid parenthesis catalan number explanation

While studying about catalan numbers, some of the applications that I came across were:
no of possible binary search trees using n nodes.
no of ways to draw non-intersecting chords using 2*n points on a circle.
no of ways to arrange n pairs of parenthesis.
While I understand the first two problems, how catalan numbers fit in their solution, I am not able to understand how they fit in the third problem.
Couldn't find any other useful resource on the internet which explains the HOW part. Everyone just says that it's the solution.
Can someone please explain.
Since others do not seem to agree with me that this question is off-topic, I now decide that it is on topic and provide and answer.
The Wikipedia is indeed confusing about the "number of ways to arrange n pairs of parentheses" (the second bullet point in this link.) Part of the confusion is that the order of the strings of parentheses does not match the order of the binary tree, which you do understand, or with many of the other examples.
Here is a way to transform a string of n pairs of parentheses which are correctly matched into a binary tree with n internal nodes. Consider the left-most parenthesis, which will be a left-parenthesis, together with its matching right-parenthesis. Turn the string into a node of the binary tree. The sub-string that is inside the currently-considered parentheses becomes the left child of this node, and the sub-string that is after (to the right) of the currently-considered right-parenthesis becomes the right child. Either or both sub-strings may be empty, and the currently-considered parentheses are simply removed. If either sub-string is not empty, continue this procedure recursively until all parentheses have been removed.
Here are two examples. Let's start with the string ((())). We start with
The considered-parentheses are the outermost ones. This becomes
(I did not bother drawing the external leaf nodes) then
then
which is Wikipedia's left-most binary tree with 3 internal nodes.
Now let's do another string, (())(). We start with
Again, the considered-parentheses are the outermost ones. This transforms to
And now the considered-parentheses are the first two, not the outermost ones. This becomes
which finally becomes
which is the second binary tree in Wikipedia's list.
I hope you now understand. Here is a list of all five possible strings of 3 pairs of parentheses that are correctly paired, followed by Wikipedia's list of binary trees. These lists now correspond to each other.
((())) (()()) (())() ()(()) ()()()

Optional sequence rule clarification

3.8. Optional Sequence:
[RULE]
Square brackets enclose an optional element sequence:
[foo bar]
is equivalent to
*1(foo bar).
The above section from RFC5234 seems not correct to me.
I think this is because the optional sequence rule [foo bar] is not only equivalent to 1*1(foo bar), but also equivalent to 1*1(bar foo). And the above example matches with default value 0, that is 0*1(foo bar).
However, [] usually means something else. So on the other hand, I think [foo bar] should mean either (foo) or (bar).
Can anyone clear this confusion for me?
The RFC defines the syntax and semantics of ABNF grammars and the quoted text defines the semantics of optional sequence syntax. It is correct by definition. Parentheses in ABNF form sequence groups, (foo bar) means foo immediately followed by bar. The number syntax in front indicates repetition, where the asterisk separates minimum number of occurences from maximum number of occurences. The minimum defaults to zero. So
*1(foo bar)
is the same as
0*1(foo bar)
meaning a sequence of foo immediately followed by bar that appears at least zero and at most one time, i.e., the sequence is optional. Since optional parts are quite frequent in formal grammars, there is a special shorthand syntax for them, namely
[foo bar]
which also means a sequence of foo immediately followed by bar that appears at least zero and at most one time. What syntactic constructs usually mean does not matter here, the specification is not reflecting on the world, it defines its own conventions.

prolog recursion

am making a function that will send me a list of all possible elemnts .. in each iteration its giving me the last answer .. but after the recursion am only getting the last answer back .. how can i make it give back every single answer ..
thank you
the problem is that am trying to find all possible distributions for a list into other lists .. the code
addIn(_,[],Result,Result).
addIn(C,[Element|Rest],[F|R],Result):-
member( Members , [F|R]),
sumlist( Members, Sum),
sumlist([Element],ElementLength),
Cap is Sum + ElementLength,
(Cap =< Ca,
append([Element], Members,New)....
by calling test .. am getting back all the list of possible answers .. now if i tried to do something that will fail like
bp(3,11,[8,2,4,6,1,8,4],Answer).
it will just enter a while loop .. more over if i changed the
bp(NB,C,OL,A):-
addIn(C,OL,[[],[],[]],A);
bp(NB,C,_,A).
to and instead of Or .. i get error :
ERROR: is/2: Arguments are not
sufficiently instantiated
appreciate the help ..
Thanks alot #hardmath
It sounds like you are trying to write your own version of findall/3, perhaps limited to a special case of an underlying goal. Doing it generally (constructing a list of all solutions to a given goal) in a user-defined Prolog predicate is not possible without resorting to side-effects with assert/retract.
However a number of useful special cases can be implemented without such "tricks". So it would be helpful to know what predicate defines your "all possible elements". [It may also be helpful to state which Prolog implementation you are using, if only so that responses may include links to documentation for that version.]
One important special case is where the "universe" of potential candidates already exists as a list. In that case we are really asking to find the sublist of "all possible elements" that satisfy a particular goal.
findSublist([ ],_,[ ]).
findSublist([H|T],Goal,[H|S]) :-
Goal(H),
!,
findSublist(T,Goal,S).
findSublist([_|T],Goal,S) :-
findSublist(T,Goal,S).
Many Prologs will allow you to pass the name of a predicate Goal around as an "atom", but if you have a specific goal in mind, you can leave out the middle argument and just hardcode your particular condition into the middle clause of a similar implementation.
Added in response to code posted:
I think I have a glimmer of what you are trying to do. It's hard to grasp because you are not going about it in the right way. Your predicate bp/4 has a single recursive clause, variously attempted using either AND or OR syntax to relate a call to addIn/4 to a call to bp/4 itself.
Apparently you expect wrapping bp/4 around addIn/4 in this way will somehow cause addIn/4 to accumulate or iterate over its solutions. It won't. It might help you to see this if we analyze what happens to the arguments of bp/4.
You are calling the formal arguments bp(NB,C,OL,A) with simple integers bound to NB and C, with a list of integers bound to OL, and with A as an unbound "output" Answer. Note that nothing is ever done with the value NB, as it is not passed to addIn/4 and is passed unchanged to the recursive call to bp/4.
Based on the variable names used by addIn/4 and supporting predicate insert/4, my guess is that NB was intended to mean "number of bins". For one thing you set NB = 3 in your test/0 clause, and later you "hardcode" three empty lists in the third argument in calling addIn/4. Whatever Answer you get from bp/4 comes from what addIn/4 is able to do with its first two arguments passed in, C and OL, from bp/4. As we noted, C is an integer and OL a list of integers (at least in the way test/0 calls bp/4).
So let's try to state just what addIn/4 is supposed to do with those arguments. Superficially addIn/4 seems to be structured for self-recursion in a sensible way. Its first clause is a simple termination condition that when the second argument becomes an empty list, unify the third and fourth arguments and that gives "answer" A to its caller.
The second clause for addIn/4 seems to coordinate with that approach. As written it takes the "head" Element off the list in the second argument and tries to find a "bin" in the third argument that Element can be inserted into while keeping the sum of that bin under the "cap" given by C. If everything goes well, eventually all the numbers from OL get assigned to a bin, all the bins have totals under the cap C, and the answer A gets passed back to the caller. The way addIn/4 is written leaves a lot of room for improvement just in basic clarity, but it may be doing what you need it to do.
Which brings us back to the question of how you should collect the answers produced by addIn/4. Perhaps you are happy to print them out one at a time. Perhaps you meant to collect all the solutions produced by addIn/4 into a single list. To finish up the exercise I'll need you to clarify what you really want to do with the Answers from addIn/4.
Let's say you want to print them all out and then stop, with a special case being to print nothing if the arguments being passed in don't allow a solution. Then you'd probably want something of this nature:
newtest :-
addIn(12,[7, 3, 5, 4, 6, 4, 5, 2], Answer),
format("Answer = ~w\n",[Answer]),
fail.
newtest.
This is a standard way of getting predicate addIn/4 to try all possible solutions, and then stop with the "fall-through" success of the second clause of newtest/0.
(Added) Suggestions about coding addIn/4:
It will make the code more readable and maintainable if the variable names are clear. I'd suggest using Cap instead of C as the first argument to addIn/4 and BinSum when you take the sum of items assigned to a "bin". Likewise Bin would be better where you used Members. In the third argument to addIn/4 (in the head of the second clause) you don't need an explicit list structure [F|R] since you never refer to either part F or R by itself. So there I'd use Bins.
Some of your predicate calls don't accomplish much that you cannot do more easily. For example, your second call to sumlist/2 involves a list with one item. Thus the sum is just the same as that item, i.e. ElementLength is the same as Element. Here you could just replace both calls to sumlist/2 with one such call:
sumlist([Element|Bin],BinSum)
and then do your test comparing BinSum with Cap. Similarly your call to append/3 just adjoins the single item Element to the front of the list (I'm calling) Bin, so you could just replace what you have called New with [Element|Bin].
You have used an extra pair of parentheses around the last four subgoals (in the second clause for addIn/4). Since AND is implied for all the subgoals of this clause, using the extra pair of parentheses is unnecessary.
The code for insert/4 isn't shown now, but it could be a source of some unintended "backtracking" in special cases. The better approach would be to have the first call (currently to member/2) be your only point of indeterminacy, i.e. when you choose one of the bins, do it by replacing it with a free variable that gets unified with [Element|Bin] at the next to last step.

Resources