Variables in Befunge - befunge

I'm coding in Befunge, and I wondered how I could make variables. I found that, using p and g, you can use your program to store variables. Example:
>&&*11p ...do so
☺ m
#.g11...gnihte
This program asks the user two numbers, multiplies them, and stores the result at the position (1, 1), which is represented by ☺ on the program. It does something, and then gets back the value stored at the top of the stack, and prints it. Then the program stops.
So the question is, do anyone know other ways to save variables on Befunge? I'm interested in discovering and sharing ways to do it.

Related

Plug Intermediate Variables into Equation

I have a MATLAB symbolic math script that calculates a couple really large matrices for me, which I then convert into a function via matlabFunction. The problem is that the matrices contain integrals, and when matlabFunction converts it it creates loads of intermediate functions (about 200, which is why I'm trying not to do this manually) which contain the variable I'm integrating over, causing errors because the variable isn't defined outside the integral() call. In the end I'm left with a bunch of nested equations that look like:
M = integral(#(s)f(t1,t2,t3,t4)) <-- t1 = g(et1,et2,et3,....) <-- et3 = h(s)
They're not all functions of every other one, but theres a lot of dependencies between them becuase of how MATLAB tried to simplify the expression. The error gets thrown when MATLAB tries to evaluate et3, notices it has an s in it (which is find to be in M because of the integral), then breaks because s isn't defined.
So far I've tried messing with the commands in MATLAB to make them stop generating terms like that but everything I did seemed to make it worse, so I've moved to excel where my current idea is something like:
Start with each equation in it's own cell
Break each cell at "=" to get the actual equations on their own
Find each placeholder variable and substitute the actual expression in
I've been trying to write a macro or lambda function for this (admittedly I don't really know how to do either of those well) but I keep getting stuck because I basically need the script to take a list of variables I want to get rid of and just keep substituting until they're all gone, but I'm not really sure how to do this in Excel.
I've also tried to use a couple "multiFindAndReplace" scripts online that let you find and replace vectors of data but none of them seem to work for this case and the SUBSTITUTE command would end up needing to be nested dozens of time to get it do what I want.
Does anyone have ideas on what to do here? Or is there a setting I'm missing in MATLAB to suppress all the intermediate terms?
EDIT: As soon as I posted this I had another idea - it looks like MATLAB generates the terms such that the et terms can't depend on one another and that no et term appears in more than one t term.
(also this is my first question, let me know if I put it in the wrong place)

build a calculator for python 3

hey everyone I need your help for my programming course, I am pursuing my undergraduate degree in psychology.
The question is:
The python application you will develop will receive the mathematical operation that the user wants to calculate and print the result on the screen.
This process will continue until the user enter "Done".
The application will terminate when the user enters the end.
Conditions and restructions:
1)you will operate with positive integers
2)only 4 operations will be used
3)remember the priority of the operation
4)you will use "*" as a cross
5)no brackets will be used
6)it is forbiddento use an external module
7)you are not responsible for the user's incorrect entries
8)bulit-in functions you can only use the following:
int
float
range
print
input
len
str
max
min
you can use all functions of list and str data structure.
there are some things to be considered:
since you write, no modules are allowed, I assume, this should only run in the CLI. This will make the exercise incredibly easier, since GUI and Python are a Love-Hate-Realionship of its own.
Assuming I understood your assign right, the user will type a list of expressions like "1*2+3/4-5" for example, typing "Done" will indicate, that these should processed and the result should be printed, right? If the User types end, the script will stop working.
Also, you will only have to handle positives, this also, and the fact that you don't have to validate the user entries, makes it very easy. I won't give you a full solution, since you should learn something with this assignment, but here are some hints, that may nudge you in the right direction.
Hints:
The input will be in a string, so handling strings will be a main task. You should look up the documentation to know, in what ways you can manipulate strings. Also have a closer look at helper functions like split, if you have the word Done more than one time in the string.
Strings are in fact just lists of letters, punctuation and numbers.
Since strings are just a list, you won't have a neatly stored 22 in there, it will be a [2][2] surrounded by an operation or the words Done or end. You will have to go through your string, break it up in smaller parts, and then from there on, call functions to do whatever there is to do.
Keep in mind, that there are literally millions of ways to achieve what you have to do, if you aren't familiar with programming, keep it simple, break it up in smaller steps and then just proceed through the exercise.
Hope this will help you. If it helped you or gave you a hint in the right direction, I would appreciate an upvote.
Have fun coding.

Guarantee of sameness of output after switching order in functional programming

I started reading some of Haskell's documentation, and there's a fundamental concept I just don't understand. I read about it in other places as well, but I want to understand it once and for all.
In many places discussing functional programing, I keep reading that if the functions you're using are pure (have no side effects, and give same response for the same input at every call) then you can switch the order in which they are called when composing them, with it being guaranteed that the output of this composed call will remain the same regardless of the order.
For example, here is an entry from the Haskell Wiki:
Haskell is a pure language, which means that the result of any
function call is fully determined by its arguments. Pseudo-functions
like rand() or getchar() in C, which return different results on each
call, are simply impossible to write in Haskell. Moreover, Haskell
functions can't have side effects, which means that they can't effect
any changes to the "real world", like changing files, writing to the
screen, printing, sending data over the network, and so on. These two
restrictions together mean that any function call can be replaced by
the result of a previous call with the same parameters, and the
language guarantees that all these rearrangements will not change the
program result!
But when I fiddle with this idea I can quickly think of examples that contradict the statement above. For instance, let's say I have two functions (I will use pseudo code rather than Haskell):
x(a)->a+3
y(a)->a*3
z(a)->x(y(a))
w(a)->y(x(a))
Now, if we execute z and w, we get:
z(5) //gives 3*5+3=18
w(5) //gives (5+3)*3=24
That being so, I think I misunderstood the promised guarantee they speak about. Can anybody explain it to me?
When you compare x(y(a)) to y(x(a)), those two expressions are not equivalent because x and y aren't called with the same arguments in each. In the first expression x is called with the argument y(a) and y is called with the argument a. Whereas in the second y is called with x(a), not a, as its argument and x is called with a, not y(a). So: different arguments, (possibly) different results.
When people say that the order does not matter, they mean that in the following code:
a = f(x)
b = g(y)
you can switch the definition of a and b without affecting their values. That is it makes no difference whether f is called before g or vice versa. This is clearly not true for the following code:
a = getchar()
b = getchar()
If you switch a and b here, their values are switched as well, because getchar returns a (possibly) different character each time that it's called. So a purely functional language can't have a function exactly like getchar.

Manipulating/Clearing Variables via Lists: Mathematica

My problem (in Mathematica) is referring to variables given in a particular array and manipulating them in the following manner (as an example):
Inputs: vars={x,y,z}, system=some ODE like x^2+3*x*y+...etc
(note that I haven't actually created variables x y and z)
Aim:
To assign values to the variables in the list "var" with the intention of inputting these values into the system of ODEs. Then, once I am done, clear the values of the variables in the array vars so that it is in its original form {x,y,z} (and not something like {x,1,3} where y=1 and z=3). I want to do this by referring to the positional elements of vars (I aim not to know that x, y and z are the actual variables).
The reason why: I am trying to write a program that can have any number of variables and ODEs as defined by the user. Since the number of variables and the actual letters used for them are unknown, it is necessary to perform manipulations with the array itself.
Attempt:
A fixed number of variables is easy. For the arbitrary case, I have tried modules and blocks, but with no success. Consider the following code:
Clear[x,y,z,vars,svars]
vars={x,y,z}
svars=Map[ToString,vars]
Module[{vars=vars,svars=svars},
Symbol[svars[[1]]]//Evaluate=1
]
then vars={1,y,z} and not {x,y,z} after running this. I have done functional programming with lists, atoms etc. Thus is makes sense to me that vars is changed afterwards, because I have changed x and not vars. However, I cannot get "x" in the list of variables to remain local. Of course I could put in "x" itself, but that is particular to this specific case. I would prefer to put something like:
Clear[x,y,z,vars,svars]
vars={x,y,z}
svars=Map[ToString,vars]
Module[{vars=vars,svars=svars, vars[[1]]},
Symbol[svars[[1]]]//Evaluate=1
]
which of course doesn't work because vars[[1]] is not a symbol or an assignment to a symbol.
Other possibilities:
I found a function
assignToName[name_String, value_] :=
ToExpression[name, InputForm, Function[var, var = value, HoldAll]]
which looked promising. Basically name_String is the name of the variable and value is its new value. I attempted to do:
vars={x,y,z}
svars=Map[ToString,vars]
vars[[1]]=//Evaluate=1
assignToName[svars[[1]],svars[[1]]]
but then something likeD[x^2, vars[[1]]] doesn't work (x is not a valid variable).
If I am missing something, or if perhaps I am going down the wrong path, I'm open to trying other things.
Thanks.
I can't say that I followed your train(s) of thought very well, so these are fragments which might help you to answer your own questions than a coherent and fully-formed answer. But to answer your final 'question', I think you may be going down some wrong path(s).
In passing, note that evaluating the expression
vars = {x,y,z}
does in fact define those three variables though it doesn't define any rewrite rules (such as values) for them.
Given a polynomial poly you can extract the variables in it with the function Variables[poly] so something like
Variables[x^2+3*x*y]
should return
{x,y}
Note that I write 'should' rather than does because I don't have Mathematica on this machine so my syntax may be a bit wonky. Note also that your example ODE is nothing of the sort but it strikes me that you can probably write a wrapper to manipulate an ODE into a form from which Variables can extract the variables. Mathematica offers a lot of other functions for picking expressions apart and re-assembling them, follow the trails from Variables. It often allows the use of functions defined on Lists on expressions with other heads too so it's always worth experimenting a bit.
There are a couple of widely applicable ways to avoid setting values of variables in Mathematica. For instance, you could write
x^2+3*x*y/.{x->2,y->3}
which will evaluate to
22
but not set values for x and y. This is a very simple example of using (sets of) replacement rules for temporary assignment of values to variables
The other way to avoid setting values for variables is to define functions using Modules or Blocks both of which define their own contexts. The documentation will tell you all about these two and the differences between them.
I can't help thinking that all your clever tricks using Symbol, ToExpression and ToString are a bit beside the point. Spend some time familiarising yourself with Mathematica's in-built functionality before going further down that route, you may well find you don't need to.
Finally, writing, in any language, expressions such as
vars=vars,svars=svars
will lead to madness. It may be syntactically correct, you may even be able to decrypt the semantics when you first write code like that, but in a week's time you will curse your younger self for writing it.

How does ArrowLoop work? Also, mfix?

I'm fairly comfortable now with the rest of the arrow machinery, but I don't get how loop works. It seems magical to me, and that's bad for my understanding. I also have trouble understanding mfix. When I look at a piece of code that uses rec in a proc or do block, I get confused. With regular monadic or arrow code, I can step through the computation and keep an operational picture of what's going on in my head. When I get to rec, I don't know what picture to keep! I get stuck, and I can't reason about such code.
The example I'm trying to grok is from Ross Paterson's paper on arrows, the one about circuits.
counter :: ArrowCircuit a => a Bool Int
counter = proc reset -> do
rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
returnA -< output
I assume that if I understand this example, I'll be able to understand loop in general, and it'll go a great way towards understanding mfix. They feel essentially the same to me, but perhaps there is a subtlety I'm missing? Anyway, what I would really prize is an operational picture of such pieces of code, so I can step through them in my head like 'regular' code.
Edit: Thanks to Pigworker's answer, I have started thinking about rec and such as demands being fulfilled. Taking the counter example, the first line of the rec block demands a value called output. I imagine this operationally as creating a box, labelling it output, and asking the rec block to fill that box. In order to fill that box, we feed in a value to returnA, but that value itself demands another value, called next. In order to use this value, it must be demanded of another line in the rec block but it doesn't matter where in the rec block it is demanded, for now.
So we go to the next line, and we find the box labelled next, and we demand that another computation fill it. Now, this computation demands our first box! So we give it the box, but it has no value inside it, so if this computation demands the contents of output, we hit an infinite loop. Fortunately, delay takes the box, but produces a value without looking inside the box. This fills next, which then allows us to fill output. Now that output is filled, when the next input of this circuit is processed, the previous output box will have its value, ready to be demanded in order to produce the next next, and thus the next output.
How does that sound?
In this code, they key piece is the delay 0 arrow in the rec block. To see how it works, it helps to think of values as varying over time and time as chopped into slices. I think of the slices as ‘days’. The rec block explains how each day's computation works. It's organised by value, rather than by causal order, but we can still track causality if we're careful. Crucially, we must make sure (without any help from the types) that each day's work relies on the past but not the future. The one-day delay 0 buys us time in that respect: it shifts its input signal one day later, taking care of the first day by giving the value 0. The delay's input signal is ‘tomorrow's next’.
rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
So, looking at the arrows and their outputs, we're delivering today's output but tomorrow's next. Looking at the inputs, we're relying on today's reset and next values. It's clear that we can deliver those outputs from those inputs without time travel. The output is today's next number unless we reset to 0; tomorrow, the next number is the successor of today's output. Today's next value thus comes from yesterday, unless there was no yesterday, in which case it's 0.
At a lower level, this whole setup works because of Haskell's laziness. Haskell computes by a demand-driven strategy, so if there is a sequential order of tasks which respects causality, Haskell will find it. Here, the delay establishes such an order.
Be aware, though, that Haskell's type system gives you very little help in ensuring that such an order exists. You're free to use loops for utter nonsense! So your question is far from trivial. Each time you read or write such a program, you do need to think ‘how can this possibly work?’. You need to check that delay (or similar) is used appropriately to ensure that information is demanded only when it can be computed. Note that constructors, especially (:) can act like delays, too: it's not unusual to compute the tail of a list, apparently given the whole list (but being careful only to inspect the head). Unlike imperative programming, the lazy functional style allows you to organize your code around concepts other than the sequence of events, but it's a freedom that demands a more subtle awareness of time.

Resources