Why does this boolean expression return false when each term is true? - io

> (Console.Read() = (int 'd'));;
d
val it: bool = true
> (Console.Read() = (int 'd')) && (Console.Read() = (int 'o'));;
val it: bool = false
It seems to terminate without calling Read, how does the compiler know to make the expression false?

You have to be careful with Read(), it also picks up the line termination character(s). You can see this if you start a clean F# interactive session and do the following:
> Console.Read();;
d
val it : int = 100
> Console.Read();;
val it : int = 13
> Console.Read();;
val it : int = 10
Obviously I did this on Windows, since the line termination was \r\n.
You should probably use ReadKey() (which you can't use in an FSI session) or ReadLine(). For example,
> Console.ReadLine() = "do";;
do
val it : bool = true
>

Related

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit

Compile-time Call Count in Nim

The following code does not compile but illustrates what I would like to do: totalTests should hold the number of time that assertEquals() is called (assertEquals() should probably be a macro for this to be possible, but I'm not familiar with this aspect of Nim yet).
Any idea how this code should be modified to enable the following code to print [1/2] and [2/2] at the beginning of each test report line?
from strutils import format
var countTested = 0
var countFailed = 0
var countPassed = 0
let totalTests = 0 # <-- need let or other compile-time type here (?)
# using proc here... macro may be needed to be able to count calls (?)
proc assertEquals*[T](testName: string, expected: T, p: (proc(): T)) =
countTested += 1
totalTests += 1 # <-- compilation error (how can we increase each time it is called?)
write(stdout, format("[$num/$total] $name: ", "num", countTested, "total", totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
countPassed += 1
else:
write(stdout, "failed\n")
countFailed += 1
when isMainModule:
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
Edit: added questions in code
Here is one way to do it. You can execute code at compile time by using a macro or a static statement. Note that there's still no way to reliably count these across multiple modules.
import macros, strutils
proc beginTests()
var countTested = 0
var countFailed = 0
var countPassed = 0
var totalTests = 0
var totalTestsCT {.compiletime.} = 0
macro endTests(): stmt =
quote do:
proc beginTests() =
totalTests = `totalTestsCT`
proc assertEqualsImpl*[T](testName: string, expected: T, p: (proc(): T)) =
countTested += 1
write(stdout, format("[$num/$total] $name: ",
"num", countTested, "total", totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
countPassed += 1
else:
write(stdout, "failed\n")
countFailed += 1
macro assertEquals*[T](testName: string, expected: T, p: (proc(): T)): stmt =
totalTestsCT += 1
quote do:
assertEqualsImpl(`testName`, `expected`, `p`)
when isMainModule:
beginTests()
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
endTests()
An alternative implementation would be to embed the tests in a custom block statement, e.g.
testSuite:
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
The testSuite macro would then count the assertions in the embedded code and initialize the variable accordingly.
Yet another solution would be to not execute the tests directly, but store them in a list and only execute them at the end.
Here is an implementation of Reimer's third suggestion, which worked best for me.
import macros, strutils
type
TestSuiteObj = object
countTested: int
countFailed: int
countPassed: int
totalTests: int
tests: seq[(proc (self: TestSuite))]
TestSuite* = ref TestSuiteObj
proc newTestSuite*(): TestSuite =
new(result)
result.countTested = 0
result.countFailed = 0
result.countPassed = 0
result.totalTests = 0
result.tests = #[]
proc assertEquals*[T](self: TestSuite, testName: string, expected: T, p: (proc(): T)) =
self.totalTests += 1
var testProc = proc(self: TestSuite) =
self.countTested += 1
write(stdout, format("[$num/$total] $name: ", "num", self.countTested, "total", self.totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
self.countPassed += 1
else:
write(stdout, "failed\n")
self.countFailed += 1
self.tests.add(testProc)
proc run*(self: TestSuite) =
self.totalTests = self.tests.len
for p in self.tests:
p(self)
var verdict = case (self.countTested == self.countPassed)
of true: "PASSED"
of false: "FAILED"
echo format("$verdict. Passed [$passed/$total] tests.", "verdict", verdict, "passed", self.countPassed, "total", self.countTested)
# Sanity
assert(self.countTested == (self.countFailed+self.countPassed))
assert(self.countTested == self.totalTests)
when isMainModule:
var suite = newTestSuite()
suite.assertEquals("test #A", 12, proc(): int = 14-2)
suite.assertEquals("test #B", 12, proc(): int = 12-2)
suite.run()

How to read a C generated binary file in Lua

I want to read a 32 bit integer binary file provided by another program. The file contains only integer and no other characters (like spaces or commas). The C code to read this file is as follows:
FILE* pf = fopen("C:/rktemp/filename.dat", "r");
int sz = width*height;
int* vals = new int[sz];
int elread = fread((char*)vals, sizeof(int), sz, pf);
for( int j = 0; j < height; j++ )
{
for( int k = 0; k < width; k++ )
{
int i = j*width+k;
labels[i] = vals[i];
}
}
delete [] vals;
fclose(pf);
But I don't know how to read this file into array using Lua.
I've tried to read this file using io.read, but part of the array looks like this:
~~~~~~xxxxxxxxyyyyyyyyyyyyyyzzzzzzzz{{{{{{{{{|||||||||}}}}}}}}}}}~~~~~~~~~xxxxxxxyyyyyyyyyyyyyyzzzzzz{{{{{{{{{{|||||||||}}}}}}}}}}}~~~~~~~~~xxyyyyyyyyyyyyyzzzzz{{{{{{|||}}}yyyyyyyyyyyz{{{yyyyyyyyÞľūơǿȵɶʢ˺̤̼ͽаҩӱľǿجٴȵɶʢܷݸ˺໻⼼ӱľǿ
Also the Matlab code to read this file is like this:
row = image_size(1);
colomn = image_size(2);
fid = fopen(data_path,'r');
A = fread(fid, row * colomn, 'uint32')';
A = A + 1;
B = reshape(A,[colomn, row]);
B = B';
fclose(fid);
I've tried a function to convert bytes to integer, my code is like this:
function bytes_to_int(b1, b2, b3, b4)
if not b4 then error("need four bytes to convert to int",2) end
local n = b1 + b2*256 + b3*65536 + b4*16777216
n = (n > 2147483647) and (n - 4294967296) or n
return n
end
local sup_filename = '1.dat'
fid = io.open(sup_filename, "r")
st = bytes_to_int(fid:read("*all"):byte(1,4))
print(st)
fid:close()
But it still not read this file properly.
You are only calling bytes_to_int once. You need to call it for every int you want to read. e.g.
fid = io.open(sup_filename, "rb")
while true do
local bytes = fid:read(4)
if bytes == nil then break end -- EOF
local st = bytes_to_int(bytes:byte(1,4))
print(st)
end
fid:close()
Now you can use the new feature of Lua language by calling string.unpack , which has many conversion options for format string. Following options may be useful:
< sets little endian
> sets big endian
= sets native endian
i[n] a signed int with n bytes (default is native size)
I[n] an unsigned int with n bytes (default is native size)
The arch of your PC is unknown, so I assume the data to read is unsigned and native-endian.
Since you are reading binary data from the file, you should use io.open(sup_filename, "rb").
The following code may be useful:
local fid = io.open(sup_filename, "rb")
local contents = fid:read("a")
local now
while not now or now < #contents do
local n, now = string.unpack("=I4", contents, now)
print(n)
end
fid:close()
see also: Lua 5.4 manual

why does scala toString give type Any?

I need to compose a String depending on the value of an Int - Scala is confusing me:
scala> val qqq: Int = -3
qqq: Int = -3
scala> qqq.toString
res17: String = -3
scala> if (qqq < 0)
| qqq.toString
res19: Any = -3
what is going on there? Why is qqq.toString a string in the first but not the last?
What happens if q >= 3 ? What type does if return then ?
e.g. if you write this:
if (qqq < 0)
"a"
else
"b"
you'll always get a String return type

scanner.nextInt() returns java.util.NoSuchElementException

This is my code, which is supposed to accept input from the user and set 2 int values. The exit function works correctly however when the input string is "5 2" for example, it sets x as 5 and throws the java.util.NoSuchElementException at the y = s2.nextInt(); line, even though there is a next int. In an example of nextInt() I saw, ints were seperated by a space and the scanner still picked up all the integers. Is mine missing something?
String exit = "-1";
Scanner s1 = new Scanner(System.in);
String input = s1.next();
Scanner s2 = new Scanner(input);
if (input.equals(exit))
Sequence.quit();
else {
x = s2.nextInt();
y = s2.nextInt();
}
If you print out your variable ìnput, you will see that it contains only "5" - since s1.next() wil stop at space.
Something like this:
String exit = "-1";
Scanner s1 = new Scanner(System.in);
int x = s1.nextInt();
if (x==-1)
Sequence.quit();
else {
y = s1.nextInt();
}

Resources