This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In Ocaml I have a "global" (ie. has file scope) array initialized with some numbers, then I do some operations on those numbers and then I call a function to sum those numbers together. Now because this array is "global" I didn't bother to pass the array as an argument and what ended up happening is that Ocaml calculated the sum of the initialized numbers (in compile time I guess) instead of after my operations on the array had happened. My question is, why does this happen? I spent about 3hrs trying to track down the bug! Does this have something to do with the no-side-effects part of Ocaml? And if so what are the rules for never having something like this happen?
Thanks
EDIT: You guys are very right, I had screwed up fundamentally. This was essentially my code
let my_array = Array.make 10 0;;
let sum_array = ...;;
let my_fun =
do_stuff_with_array args;
sum_array;;
So of course sum_array was being calculated beforehand. Changed it to this and it worked, is this the best solution?
let my_array = Array.make 10 0;;
let sum_array _ = ...;;
let my_fun =
do_stuff_with_array args;
sum_array ();;
OCaml did certainly not compute the sum of the elements of your array "at compile time". There is something you haven't understood about OCaml evaluation order. It's hard to answer your question because there is no question really, it just tells us that you're a bit lost on this topic.
This is fine if we can help you by explaining things to you. It would help, however, if you could help us in spotting where your incomprehension lies, by :
giving a small source code example that does not behave as you expect
and explaining which behavior you would expect and why
The general thing to know about OCaml evaluation order is that, in a module or file, sentences are evaluated from top to bottom, that when you write let x = a in b the expression a is always evaluated before b, and that a function fun x -> a (or equivalent form such as let f x = a) evaluates to itself, without evaluating a at all -- this happens at application time.
Some people like to have a "main" sentence that contains all the side-effects of your code. It is often written like that:
let () =
(* some code that does side-effect *)
If you write code that evaluates and produce side-effects in other part of your file, well, they will be evaluated before or after this sentence depending on whether they are before or after it.
Related
Why this Fortran code is incorrect?
function foo(x)
real x
real, dimension(3) :: foo
foo = (/1, 2, 3/)
end
... and in main program
print*, foo(x)(1)
Why we cannot access element in function result directly?
While you ponder your own question
Why we cannot access element in function result directly?
I suggest you also write lines, in your main program, such as
res = foo(x) ! having taken care to declare res appropriately
print*, res(1)
and get on with your coding. It's just not syntactically-correct to index a function call the way you've tried.
So one answer to your original question is because that's the way Fortran's syntax is defined to which you might be prompted to respond why is Fortran's syntax defined that way ? Even if this process turns up an answer in the form of reference to the roots of the design of Fortran (now over 50 years old) you're still going to have to modify your code to align with Fortran's syntax. For sure your compiler isn't going to say you know, what you've written is better than the syntax I've been programmed to accept, I'll compile that up right now ...
The answer by High Performance Mark tells all needed. As you're after syntactic niceness I'll address one thing in there: "having taken care to declare res appropriately".
One could use an associate construct to hide this a little.
associate (res => foo(x))
print *, res(1)
end associate
This changes nothing in that answer other than reducing junk declarations.
I am reading this excellent article by Mark Seemann.
In it, he gives a simple demonstration of using the free monad to model interactions using pure functions.
I understand it enough to be able to write such a program, and I can appreciate the virtues of such an approach. There is one bit of code though, that has me wondering about the implications.
let rec bind f = function
| Free instruction -> instruction |> mapI (bind f) |> Free
| Pure x -> f x
The function is recursive.
Given that this is not tail recursive, does that mean that the number of instructions I include is limited by stack space, because every time I add an instruction, it has to unwrap the whole thing to add it?
Similarly to the above, does this imply a higher startup time because each new instruction has to go further down to be added? It might be negligible, but that is not the point of the question; I am trying to understand the theory, not the practicality.
If the answer to the above questions is 'Yes', would an alternative implementation along the lines of (make a list of instructions in the order you want them, then process the list in reverse order such that each instruction gets added to the top of your program, rather than deep down in the bottom) be preferable?
I may (probably) have missed something fundamental here that means that the recursion never has to go very far, please let me know.
I think the answer to the first two questions is "it depends" - there is some overhead associated with free monads and you can certainly run into stack overflows, but you can always use an implementation that avoids this and if you're doing I/O, then the overhead probably is not too bad.
I think the much bigger issue with free monads is that they are just too complicated abstraction. They let you solve one problem (abstracting over how you run code with lots of iteractions), but at a cost that you are making code very complicated. Most of the time, I think you can just keep a "functional core" as a nice testable pure part and "imperative wrapper" around it that is simple enough that you do not need to test it and abstract over it.
Free monads are very universal way of modeling this and you could use a more concrete representation. For reading and writing, you could do:
type Instruction =
| WriteLine of string
| ReadLine of (string -> Instruction list)
As you can see, this is not just a simple list - ReadLine is tricky, because it takes a function that, when called with the string from the console, produces more instructions (that may, or may not, depend on this string):
let program =
[ yield WriteLine "Enter your name:"
yield ReadLine (fun name ->
[ if name <> "" then
yield WriteLine ("Hello " + name) ] ) ]
This says "Hello " but only when you enter non-empty name, so it shows how the instructions depend on the name you read. The code to run a program then looks like this:
let rec runProgram program =
match program with
| [] -> ()
| WriteLine s :: rest ->
Console.WriteLine s
runProgram rest
| ReadLine f :: rest ->
let input = Console.ReadLine()
runProgram (f input # rest)
The first two cases are nice and fully tail-recursive. The last case is tail-recursive in runProgram, but it is not tail recursive when calling f. This should be fine, because f only generates instructions and does not call runProgram. It also uses slow list append #, but you could fix that by using a better data structure (if it actually turned out to be a problem).
Free monads are basically an abstraction over this - but I personally think that they are going one step too far and if I really needed this, then something like the above - with concrete instructions - is better solution because it's simpler.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
A simplified description of the problem:
There are exactly maxSize people shopping in a store. Each of them has a shopping list, containing the price of items (as integers). Using Fortran arrays, how can I represent all the shopping lists. The shopping lists may contain any number of items (1, 10, 1000000000).
(NOTE: The actual problem is far more complicated. It is not even about shopping.)
The lazy approach would be:
integer :: array(maxSize, A_REALLY_BIG_NUMBER)
However, this is very wasteful, I basically want the second dimension to be variable, and then allocate it for each person seperately.
The obvious attempt, doomed to failure:
integer, allocatable :: array(:,:)
allocate(array(maxSize, :)) ! Compiler error
Fortran seems to require that arrays have a fixed size in each dimension.
This is wierd, since most languages treat a multidimensional array as an "array of arrays", so you can set the size of each array in the "array of arrays" seperately.
Here is something that does work:
type array1D
integer, allocatable :: elements(:) ! The compiler is fine with this!
endtype array1D
type(array1D) :: array2D(10)
integer :: i
do i=1, size(array2D)
allocate(array2D(i)%elements(sizeAt(i))
enddo
If this is the only solution, I guess I will use it. But I was kind of hoping there would be a way to do this using intrinsic functions. Having to define a custom type for such a simple thing is a bit annoying.
In C, since an array is basically a pointer with fancy syntax, you can do this with an array of pointers:
int sizeAt(int x); //Function that gets the size in the 2nd dimension
int * array[maxSize];
for (int x = 0; x < maxSize; ++x)
array[x] = (int*)(calloc(sizeAt(x) , sizeof(int)));
Fortran seems to have pointers too. But the only tutorials I have found all say "NEVER USE THESE EVER" or something similar.
You seem to be complaining that Fortran isn't C. That's true. There are probably a near infinite number of reasons why the standards committees chose to do things differently, but here are some thoughts:
One of the powerful things about fortran arrays is that they can be sliced.
a(:,:,3) = b(:,:,3)
is a perfectly valid statement. This could not be achieved if arrays were "arrays of pointers to arrays" since the dimensions along each axis would not necessarily be consistent (the very case you're trying to implement).
In C, there really is no such thing as a multidimensional array. You can implement something that looks similar using arrays of pointers to arrays, but that isn't really a multidimensional array since it doesn't share a common block of memory. This can have performance implications. In fact, in HPC (where many Fortran users spend their time), a multi-dimensional C array is often a 1D array wrapped in a macro to calculate the stride based on the size of the dimensions. Also, dereferencing a 7D array like this:
a[i][j][k][l][m][n][o]
is a good bit more difficult to type than:
a(i,j,k,l,m,n,o)
Finally, the solution that you've posted is closest to the C code that you're trying to emulate -- what's wrong with it? Note that for your problem statement, a more complex data-structure (like a linked-list) might be in order (which can be implemented in C or Fortran). Of course, linked-lists are the worst as far as performance goes, but if that's not a concern, it's probably the correct data structure to use as a "shopper" can decide to add more things into their "cart", even if it wasn't on the shopping list they took to the store.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Help me come up with an obfuscated way to multiply a number by 2, accurate to the second decimal.
Ideas:
use the Russian multiplication technique
trig / other mathematical identities
monte carlo methods
but of course bonus points for CS trickery
edit:
Just remembered that it's probably more appropriate to think of this in terms of significant figures, not accurate decimal places. So go for 4 matching leading digits.
The following perl one-liner doubles the first command-line argument:
perl -e '$/=$\=shift;map$\+=$//(++$|+$|)**$_,(++$...$=);print'
You may say that using perl is cheating because everything is obfuscated in perl. You would not be entirely wrong.
Here's a slightly different approach in (unobfuscated) python:
import math
def double(n) :
if n == 0 :
return 0
a = b = n
for i in range(1,100) :
a = 2 + 1.0/a
a = a - 1
for i in range(1,100) :
b = a * b
a = math.sqrt(a)
return b
If the goal is obfuscation for the sake of it, there is nothing like some red herrings and useless object structure to distract whoever is reading the code from your true goals. For example, instead of using any number directly, you could pull it from a dictionary, or get it from the length of another object (say a list of size two), or even better, hide the number 2 in some string, and then regex it out with an awkward-to-read pattern.
Since you want to make the simple complex, you could do some goofy things with complex numbers. Assuming you have any libraries available for complex arithmetic, you could, for example, leverage the most beautiful equation in mathematics: e^(pi*i) + 1 = 0. For instance in Java using Apache Commons Math (of course you would obfuscate the variable names):
Complex i = new Complex(0, 1);
double two = i.multiply(Math.PI).exp().getReal() + 3 + i.multiply(Math.PI).exp().getImaginary()*5;
The real part is -1, so adding 3 gives us 2. The imaginary part is 0, so multiplying it by 5 and adding it is a red herring that doesn't do anything.*
As long as this is for fun, you can try other variants using other similar identifies. However, I don't recommend relying on this type of thing to truly obfuscate code within a real product. There are packages that obfuscate code for you, and automatically changing variable names to gibberish goes a long way to deterring humans (while still letting the code stay readable for the sanity of developers).
*In floating point arithmetic the imaginary part might not be exactly 0, but you said you were interested in accuracy to two decimal places.
Since this is homework I don't want to just give you the answer but consider the number as it is represented in binary and what sort of binary operands are at your disposal that might help doing in doing multiplication.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have defined this pseudo-code for recognising strings using a relaxed-trie where the function Next[u,x] gives the set of nodes with u-edges from u ( basically the set of nodes such that (u,x,v) is an edge in T).
Here it is:
U := {1};
while s ≠ λ and U ≠ Ø do
U:= U in u Union Next [u, head(s)];
s:= tail(s)
od;
if U ≠ Ø then
if Final[u] for some u in U then
Accept
else reject
fi
else
reject
fi
Basically I have defined a postcondition for the loop, and given a loop invariant ( I think I have these elements covered, but if you think it will help to explain it go for it).
So I need to give a short argument stating why the invariant is invariant, (ie how it is preserved by the loop body, when the loop condition holds).
I then need to extend this pseudocode such that it can move to a new node without advancing the input :
(I think I would do this by adding another array (say Null) where Null[u] is the set of states it can move to from u without advancing the input)
It should also be changed such that each iteration before looking at the input all states can be reached from a state in U without advancing the input.
Thanks for all your help, am finding these two steps quite difficult, but think my psuedo-code for the first part is fine