F# poorly formatted module - module

Hi what is wrong with my code below, my errors are:
unmatched { which is mostly due to my tabs,
Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }'
Incomplete structured construct at or before this point in expression
module records =
let debate(irthes:DateTime) =
{
let mutable manch = nexttime(irthes)
let mutable array1: DateTime array = Array.zeroCreate 480
for i in 0 .. 480-1 do
Array.set array1 i (manch)
let next = Array.get array1 i
let! manch=nexttime(next)
return(array1)
}

I suppose you want something like this:
module records =
let debate(irthes:DateTime) =
let mutable manch = nexttime(irthes)
let array1: DateTime array = Array.zeroCreate 480
for i in 0 .. 480-1 do
array1.[i] <- manch
manch <- nexttime manch
array1
Here are things that were wrong with the code:
You are not using computation expressions (like asynchronous workflows), so there is no need to wrap things in curly brackets.
To return a value you do not need return. Just use the value as the last expression of the body
The let! construct does not mean assign. It has a fairly special meaning in computation expressions. To mutate manch, you can write manch <- nexttime(next).
Not an error, but you do not need to mark the array as mutable. You are mutating its contents, not the array1 variable.
You can make the code nicer by using arr.[i] <- v to write to an array and arr.[i] to read from an array. I also do not understand why you were reading a value immediately after writing it.

There's not that much that's even valid about what you're trying to do. First off, it seems you're trying to initialize a record -- to do so, you have to assign the fields to values with =, like so:
type Person = { name: string; address: string }
let joe = { name = "Joe Smith"; address: "1600 Pennsylvania Avenue NW, Washington, 20500" }
Also, F# doesn't have an early exit (return); the result of any function/method is simply the result of the last expression:
let increment n = n + 1
Hence no return n + 1. Also, let! is only used in computation expressions. However, if you want to mutate a variable, foo for example, to 42, use foo <- 42. One last thing that I see: the line with return(array1) is lacking another space of indentation -- it really matters!
It looks like you might be copy-pasting code without knowing what any of it means -- that doesn't often work out too well. If this is the case, try to understand exactly how certain features in F# work by testing them out yourself. It'll go a lot smoother in the long run.

Related

What is the most efficient way to join one list to another in kotlin?

I start with a list of integers from 1 to 1000 in listOfRandoms.
I would like to left join on random from the createDatabase list.
I am currently using a find{} statement within a loop to do this but feel like this is too heavy. Is there not a better (quicker) way to achieve same result?
Psuedo Code
data class DatabaseRow(
val refKey: Int,
val random: Int
)
fun main() {
val createDatabase = (1..1000).map { i -> DatabaseRow(i, Random()) }
val listOfRandoms = (1..1000).map { j ->
val lookup = createDatabase.find { it.refKey == j }
lookup.random
}
}
As mentioned in comments, the question seems to be mixing up database and programming ideas, which isn't helping.
And it's not entirely clear which parts of the code are needed, and which can be replaced. I'm assuming that you already have the createDatabase list, but that listOfRandoms is open to improvement.
The ‘pseudo’ code compiles fine except that:
You don't give an import for Random(), but none of the likely ones return an Int. I'm going to assume that should be kotlin.random.Random.nextInt().
And because lookup is nullable, you can't simply call lookup.random; a quick fix is lookup!!.random, but it would be safer to handle the null case properly with e.g. lookup?.random ?: -1. (That's irrelevant, though, given the assumption above.)
I think the general solution is to create a Map. This can be done very easily from createDatabase, by calling associate():
val map = createDatabase.associate{ it.refKey to it.random }
That should take time roughly proportional to the size of the list. Looking up values in the map is then very efficient (approx. constant time):
map[someKey]
In this case, that takes rather more memory than needed, because both keys and values are integers and will be boxed (stored as separate objects on the heap). Also, most maps use a hash table, which takes some memory.
Since the key is (according to comments) “an ascending list starting from a random number, like 18123..19123”, in this particular case it can instead be stored in an IntArray without any boxing. As you say, array indexes start from 0, so using the key directly would need a huge array and use only the last few cells — but if you know the start key, you could simply subtract that from the array index each time.
Creating such an array would be a bit more complex, for example:
val minKey = createDatabase.minOf{ it.refKey }
val maxKey = createDatabase.maxOf{ it.refKey }
val array = IntArray(maxKey - minKey + 1)
for (row in createDatabase)
array[row.refKey - minKey] = row.random
You'd then access values with:
array[someKey - minKey]
…which is also constant-time.
Some caveats with this approach:
If createDatabase is empty, then minOf() will throw a NoSuchElementException.
If it has ‘holes’, omitting some keys inside that range, then the array will hold its default value of 0 — you can change that by using the alternative IntArray constructor which also takes a lambda giving the initial value.)
Trying to look up a value outside that range will give an ArrayIndexOutOfBoundsException.
Whether it's worth the extra complexity to save a bit of memory will depend on things like the size of the ‘database’, and how long it's in memory for; I wouldn't add that complexity unless you have good reason to think memory usage will be an issue.

why are objects clipping behind each other?

I'm making a script that sorts the depth for my objects by prioritizing the y variable, but then afterwards checks to see if the objects that are touching each other have a higher depth the further to the right they are, but for some reason the last part isn't working.
Here's the code:
ds_grid_sort(_dg,1,true);
_yy = 0;
repeat _inst_num
{
_inst = _dg[# 0, _yy];
with _inst
{
with other
{
if (x > _inst.x and y = _inst.y)
{
_inst.depth = depth + building_space;
}
}
}
_yy++;
}
I've identified that the problem is that nothing comes out as true when the game checks the y = _inst.y part of the _inst statement, but that doesn't make any sense seeing how they're all at the same y coordinate. Could someone please tell me what I'm doing wrong?
As Steven mentioned, it's good practice to use double equal signs for comparisons (y == _inst.y) and a single equals sign for assignments (_yy = 0;), but GML doesn't care if you use a single equals sign for comparison, so it won't be causing your issue. Though it does matter in pretty much every other language besides GML.
From what I understand, the issue seems to be your use of other. When you use the code with other, it doesn't iterate through all other objects, it only grabs one instance. You can test this by running this code and seeing how many debug messages it shows:
...
with other
{
show_debug_message("X: "+string(x)+"; Y: "+string(y));
...
You could use with all. That will iterate through all objects or with object, where object is either an object or parent object. That will iterate through all instances of that object. However, neither of these functions check whether the objects overlap (it's just going to iterate over all of them), so you'll have to check for collisions. You could do something like this:
...
with all
{
if place_meeting(x, y, other)
{
if (x > _inst.x and y = _inst.y)
{
_inst.depth = depth + building_space;
}
}
...
I don't know what the rest of your code looks like, but there might be an easier way to achieve your goal. Is it possible to initially set the depth based on both the x and y variables? Something such as depth = -x-y;? For people not as familiar with GameMaker, objects with a smaller depth value are drawn above objects with higher depth values; that is why I propose setting the depth to be -x-y. Below is what a view of that grid would look like (first row and column are x and y variables; the other numbers would be the depth of an object at that position):
Having one equation that everything operates on will also make it so that if you have anything moving (such as a player), you can easily and efficiently update their depth to be able to display them correctly relative to all the other objects.
I think it should be y == _inst.y.
But I'm not sure as GML tends to accept such formatting.
It's a better practise to use == to check if they're equal when using conditions.

Why is a variable not immutable?

Why is varx not immutable in this code?
y = { g = 'a' }
z = { g = 1 }
varx = foo y
varx = foo z
Anybody knows? Thanks.
I guess that this code is executed in the Elm REPL. Immutable variables behave a little differently there. From the Beginning Elm book:
https://elmprogramming.com/immutability.html
The repl works a little differently. Whenever we reassign a different value to an existing constant, the repl essentially rebinds the constant to a new value. The rebinding process kills the constant and brings it back to life as if the constant was never pointing to any other value before.
When compiling Elm code the ordinary way with Elm make, this code would lead to an error.

perl6 placeholder variable and topic variable

There are both placeholder variables and topic variables in Perl 6. For example, the following two statements are the same
say ( $_ * 2 for 3, 9 ); # use topic variables
say ( { $^i * 2 } for 3, 9 ); # use placeholder variables
It seems to me, the only benefit one gets from topic variables is saving some keyboard strokes.
My question is: Is there a use case, where a topic variable can be much more convenient than placeholder variables?
The topic can have method calls on it:
say ( .rand for 3,9);
Compared to a placeholder:
say ( {$^i.rand} for 3,9);
Saves on typing a variable name and the curly braces for the block.
Also the topic variable is the whole point of the given block to my understanding:
my #anArrayWithALongName=[1,2,3];
#anArrayWithALongName[1].say;
#anArrayWithALongName[1].sqrt;
#OR
given #anArrayWithALongName[1] {
.say;
.sqrt;
}
That's a lot less typing when there are a lot of operations on the same variable.
There are several topic variables, one for each sigil: $, #, %_ and even &_ (yep, routines are first-class citizens in Perl6). To a certain point, you can also use Whatever (*) and create a WhateverCode in a expression, saving even more typing (look, ma! No curly braces!).
You can use the array form for several variables:
my &block = { sum #_ }; say block( 2,3 )
But the main problem they have is that they are single variables, unable to reflect the complexity of block calls. The code above can be rewritten using placeholder variables like this:
my &block = { $^a + $^b }; say block( 2,3 )
But imagine you've got some non-commutative thing in your hands. Like here:
my &block = { #_[1] %% #_[0] }; say block( 3, 9 )
That becomes clumsy and less expressive than
my &block = { $^divi %% $^divd }; say block( 3, 9 ); # OUTPUT: «True␤»
The trick being here that the placeholder variables get assigned in alphabetical order, with divd being before divi, and divi being short for divisible and divd for divided (which you chould have used if you wanted).
At the end of the day, there are many ways to do it. You can use whichever you want.

OCaml - Rejecting negative numbers

I want to create a program that sums two ints. However, they must be both positive.
I wanted to write something like this:
let n = read_int ()
while n<=0 do
let n = read_int ()
done
So it would read the number again, until it checks that it's positive.
What is the correct way to do this?
To add to the other answers, a recursive function that would do the job would look like
let rec read_next_non_negative_int () =
let n = read_int () in
if n < 0 then
read_next_non_negative_int ()
else
n
Let's figure out how it works. It reads an integer n. If n is negative, that's no good, so we try the whole thing again. However otherwise, we have found a non-negative n so we just return it.
This is a very basic example of a recursive function. Recursive functions always have :
A call to the function itself inside their own definition. Here, it's in the then clause of our test.
An recursion termination, which is basically a return statement in many languages, but in OCaml you don't explicitly writes return. Here, it's the n in the else statement.
Without a self-call, the function wouldn't be recursive, and without recursion termination, it would loop forever. So when trying to write a recursive function, always think "What's the scenario in which there is no need to call the function again", and write that as your recursion termination(s). Then think "And when is it that I need to call my function again, and with which parameter", and write the self-call(s).
Your code isn't syntactically valid, but even if it were valid it's based on the idea of changing the value of a variable, which isn't possible in OCaml.
In imperative programming you can change the value of n until it looks like what you want. However, OCaml is a functional language and its variables are bound to one value permanently.
The n that appears in while n < = ... is not the same n that appears in let n = read_int (). The keyword let introduces a new local variable.
It might help to imagine writing a recursive function that returns the next non-negative value that it reads in using read_int. If it doesn't get a good value, it can call itself recursively.