What can be used instead of Either in DAML? - daml

when am creating choice using either function,whenever error has been occurs means then they returns values to the left side of the either,which is terminating the complete template itself that is not proceeding further for other scenario execution,how to do both same functionality in daml instead of Either.

If execution doesn't proceed further, then the error is not handled. Moreover, a Left can't be simply ignored. Consider this DAML function:
steps : Bool -> Either Int Bool
steps q = do
a <- if q then Left 1 else Right "foobar"
return $ a == "foobar"
a is a Text, which is only present if the Either is Right. So if the Either is Left, execution cannot proceed to the last line, because there is nothing to assign to a.
It wouldn't do to change this behavior just because you might get an Either Text Text. So in this case, too, the variable will only be bound if it's Right.
It also wouldn't do to change behavior just because you removed the variable. For example,
steps2 : Bool -> Either Int Bool
steps2 q = do
if q then Left 1 else Right "foobar"
return q
If the semantics suddenly "just kept going" because you eliminated an unused variable binding, that would be incredibly inconsistent and confusing. So it stops right there on Left, just as if a <- was still there.
The thing is, this is not just about Either; this holds for all "error-reporting-style" actions, because they are all characterized by "I don't have a value to bind to your variable", so execution can never proceed further in any do, even if you use an "alternative" to Either.
You must handle the error right there if you want execution to proceed; in other words, if you have a Left, you have to come up with a Right if you want it to keep going, and that has equivalence in any action that features error-reporting, because they all have missing a values that you must come up with. Indeed, the meaning of error for all is "I can't come up with a value for your a <- or whatever else you're doing".

Related

Filling eltType with nil values

So I have a chapel issue i can't seem to figure out. I have a queue that one can set size. The only thing is is that it's setting size and filling the queue with a bunch of 0s (which make's sense). I'm trying to fill the queue with null rather than numerical values so later on when I work on the add method I can check if queue is null. I have attached an image of how everything is set up. Let me know if you guys have any guidance or ideas.
The error that i'm getting is:
error: type mismatch in assignment from string to int(64)
I must be doing it the wrong way here.
The error you are seeing is about the line:
elements[i] = 'nil';
'nil' is a string, not the nil value, which is written as just nil without any quotes. Assigning a string to a slot in an array of int(64) doesn't work, so the compiler issues an error.
In Chapel only classes can have a nil value though, so you'll need to use a different way to keep track of which positions in the elements array are filled.
One way to do that would be to add two new integers to your class that keep track of the first and last positions containing valid values. As you add values to the queue the last position increases, and as you remove values the first position increases. When either of those values passes the end of the array, it wraps around back to the front. If last ever catches first, then the array is full. If first ever catches last then the array is empty.
A few other things I think should be corrected in your code are:
use semaphore.chpl; Use statements work with module names, not filenames, so this should probably be use semaphore;.
If I'm understanding your intent here, this code is trying to set the size of the elements array to 5.
var elementsDomain: domain(1);
var elements: [elementsDomain] eltType = 5;
The array's domain controls the size of the array, so the way to set the array size is through the domain:
var elementsDomain: domain(1) = {0..#5};
var elements: [elementsDomain] eltType;
elementsDomain = (0..capacity - 1); is setting elementsDomain to a range literal value. This works since the domain is 1-dimensional, but to make it more clear, you can set it to a domain literal value instead: {0..capacity - 1}.

Erlang - ** exception error: no match of right hand side value

I have a problem with pattern match of json formatted string.
Here I add a shorted version (just changed long json string to "{\"jsondata\"}"
So i have this pattern match which is sucessfull:
> MyData2={ok,{{"HTTP/1.1",200,"OK"},
[{"connection","Keep-Alive"},
{"date","Thu, 10 Sep 2015 12:03:49 GMT"},
{"server","Apache/2.4.7 (Ubuntu)"},
{"vary","X-Auth-Token"},
{"content-length","1171"},
{"content-type","application/json"},
{"x-openstack-request-id",
"req-31b4efc1-2af4-4130-b7a8-01d94b456096"},
{"keep-alive","timeout=5, max=100"}],
"{\"jsondata\"}"}}.
After that I run the following:
> {ok,{{"HTTP/1.1",ReturnCode, State},B,J}}=MyData2.
unfortunatelly i get
If I change "{\"jsondata\"}" to "jsondata" the last pattern match works fine
I have no Idea how to extract the json and get in J the "{\"jsondata\"}"
I`ll appriciate any idea
** exception error: no match of right hand side value
Your pattern matching operation works perfectly. I think the problem is, that one of the variables ReturnCode, State, B or J is already bound.
Lets assume the variable J is already bound to a value, and the other variables are not. Depending on this value, the pattern matching operation
{ok,{{"HTTP/1.1",ReturnCode, State},B,J}} = MyData2.
either succeeds or not.
Case 1:J is already bound to "{\"jsondata\"}"
Your pattern-match will succeed and the values of the unbound variables (ReturnCode, State and B) will be set, according to the pattern of MyData2.
Case 2:J is already bound to "{jsondata}"
The J-variable on the right hand side won't match the pattern of MyData2 on the left hand side. Thus the execution fails with an exception.
This also happens on the shell if you forget to clear your variables with f(Variable).

How to use Eiffel functions?

So I'm just starting to learn Eiffel. One of the first exercises in the book I'm using says to make a function that does base^exp without using ^. I've copied my code below.
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create power(2;3)
printf("2 to the power of 3 is " + answer)
end
power(base : REAL; exp : INTEGER) : REAL
-- computers base raised to the bower of exp without using ^
local
remain : INTEGER
do
remain := exp
if remain = 0 then
result := 1
else
from
until
remain = 0
loop
result := result * result
remain := remain -1
end
end
end
end
How do I use this? Do I need it on the same level as feature{NONE}'s make? I know how I'm calling it is wrong, and I can't find anything in the chapter I just read, or online on how to pass parameters into it or how to use it's results.
There are several issues with the original code:
create is used to create an object, but you are not going to create anything, but to get a result of a computation of the function power by calling it. Therefore the keyword create is not needed.
You are using an entity answer to report the result of evaluation on a screen. However it is not declared anywhere. I believe the proper place would be a local variable declaration section.
The entity answer is not initialized to the result of the function power. This is usually done by an assignment instruction.
Feature arguments are separated by a comma, not by a semicolon.
From the original code it's unclear what is the type of the variable answer. Assuming it matches the type of the function power, before adding it to a string, it needs to be converted to a string. This is done by calling the feature out.
The standard feature for printing a string to a console is print, not printf.
Combining the critical points above, we get
make
-- Run application.
local
answer: REAL
do
answer := power(2, 3)
print ("2 to the power of 3 is " + answer.out)
end
After that the code can be compiled. Now less critical points:
It is a good style to put features to a dedicated feature clauses, so I would add a line like feature -- Basic operations before the feature power.
The implementation of the feature power has at least two problems. I'm not going to detail them here, but would give two hints instead:
by default numeric Result is initialized to 0, this needs to be taken into account for operations that use it without first assigning any other value
even though an argument base is passed to the function power it remains unused in the original version of the code

What is the difference in purpose of TO and MAKE, and where are they documented?

I feel like I understand MAKE as being a constructor for a datatype. It takes two arguments... the first the target datatype, and the second a "spec".
In the case of objects it's fairly obvious that a block of Rebol data can be used as the "spec" to get back a value of type object!
>> foo: make object! [x: 10 y: 20 z: func [value] [print x + y + value] ]
== make object! [
x: 10
y: 20
]
>> print foo/x
10
>> foo/z 1
31
I know that if you pass an integer when you create a block, it will preallocate enough underlying memory to hold a block of that length, despite being empty:
>> foo: make block! 10
== []
That makes some sense. If you pass a string in, then you get the string parsed into Rebol tokens...
>> foo: make block! "some-set-word: {String in braces} some-word 12-Dec-2012"
== [some-set-word: "String in braces" some-word 12-Dec-2012]
Not all types are accepted, and again I'll say so far... so good.
>> foo: make block! 12-Dec-2012
** Script error: invalid argument: 12-Dec-2012
** Where: make
** Near: make block! 12-Dec-2012
By contrast, the TO operation is defined very similar, except it is for "conversion" instead of "construction". It also takes a target type as a first parameter, and then a "spec". It acts differently on values
>> foo: to block! 10
== [10]
>> foo: to block! 12-Dec-2012
== [12-Dec-2012]
That seems reasonable. If it received a non-series value, it wrapped it in a block. If you try an any-block! value with it, I'd imagine it would give you a block! series with the same values inside:
>> foo: to block! quote (a + b)
== [a + b]
So I'd expect a string to be wrapped in a block, but it just does the same thing MAKE does:
>> foo: to block! "some-set-word: {String in braces} some-word 12-Dec-2012"
== [some-set-word: "String in braces" some-word 12-Dec-2012]
Why is TO being so redundant with MAKE, and what is the logic behind their distinction? Passing integers into to block! gets the number inside a block (instead of having the special construction mode), and dates go into to block! making the date in a block instead of an error as with MAKE. So why wouldn't one want a to block! of a string to put that string inside a block?
Also: beyond reading the C sources for the interpreter, where is the comprehensive list of specs accepted by MAKE and TO for each target type?
MAKE is a constructor, TO is a converter. The reason that we have both is that for many types that operation is different. If they weren't different, we could get by with one operation.
MAKE takes a spec that is supposed to be a description of the value you're constructing. This is why you can pass MAKE a block and get values like objects or functions that aren't block-like at all. You can even pass an integer to MAKE and have it be treated like an allocation directive.
TO takes a value that is intended to be more directly converted to the target type (this value being called "spec" is just an unfortunate naming mishap). This is why the values in the input more directly correspond to the values in the output. Whenever there is a sensible default conversion, TO does it. That is why many types don't have TO conversions defined between them, the types are too different conceptually. We have fairly comprehensive conversions for some types where this is appropriate, such as to strings and blocks, but have carefully restricted some other conversions that are more useful to prohibit, such as from none to most types.
In some cases of simple types, there really isn't a complex way to describe the type. For them, it doesn't hurt to have the constructors just take self-describing values as their specs. Coincidentally, this ends up being the same behavior as TO for the same type and values. This doesn't hurt, so it's not useful to trigger an error in this case.
There are no comprehensive docs for the behavior of MAKE and TO because in Rebol 3 their behavior isn't completely finalized. There is still some debate in some cases about what the proper behavior should be. We're trying to make things more balanced, without losing any valuable functionality. We've already done a lot of work improving none and binary conversions, for instance. Once they are more finalized, and once we have a place to put them, we'll have more docs. In the meanwhile most of the Rebol 2 behavior is documented, and most of the changes so far for Rebol 3 are in CureCode.
Also: beyond reading the C sources for the interpreter, where is the
comprehensive list of specs accepted by MAKE and TO for each target
type?
May not be that useful, since it's red specific:
comparison-matrix
conversion-matrix
But it does at least mention if the behaviour is similar or different from rebol

Implementing arrays using a stack

My programming language has no arrays, no lists, no pointers, no eval and no variable variables. All it has:
Ordinary variables like you know them from most programming languages: They all have an exact name and a value.
One stack. Functions provided are: push (add element to top), pop (remove element from top, get value) and empty (check if stack is empty)
My language is turing-complete. (Basic arithmetics, conditional jumps, etc implemented) That means, it must be possible to implement some sort of list or array, right?
But I have no idea how...
What I want to achieve: Create a function which can retrieve and/or change an element x of the stack.
I could easily add this function in the implementation of my language, in the interpreter, but I want to do it in my programming language.
"Solution" one (Accessing an element x, counting from the stack top)
Create a loop. Pop off the element from the stack top x times. The last element popped of is element number x. I end up with a destroyed stack.
Solution two:
Do the same as above, but store all popped off values in a second stack. Then you could move all elements back after you are done. But you know what? I don't have a second stack!
Sounds like a homework question, as it flexing random bits of Computer Science...
I think you would want to use recursion to do this. Say I have something like this..
Queue globalQueue = new Queue();
Then I could have code that got element X like this
public Object findElement(stepsToTake s) {
if (queue.empty()) {
throw new EmptyQueueYouFailException();
}
Object o = queue.pop();
if (s == 0) {
queue.push(o);
return o;
}
Object actualResult = findElement( s - 1 );
//restore this element to the stack
queue.push(o);
//return actual result
return actualResult;
}
So more likely than not I made some bug... have not thought through it super well. Especially worried that I will reorder the stack because of the order of my calls..
Hopefully this can get you thinking along the right lines to get a solution?
Do you have procedure calls and recursion? Then you do have a second stack, the call stack. If not, are you sure it's Turing complete, and not just a PDA?
If you have only one stack, this is equivalent to a pushdown automaton, which can recognize context-free languages, and is not Turing-complete. Your proof of Turing completeness should inform how you can implement freeform memory access.
In general, to prove Turing-completeness, you must be able to show how your language can move left to right over a tape (or indirectly simulate this process), which corresponds roughly to a single higher-level array.