Must a zig function called at compile-time be pure? - zig

https://ziglang.org/documentation/master/#struct
// Functions called at compile-time are memoized. This means you can
// do this:
try expect(LinkedList(i32) == LinkedList(i32));
IIUC, if functions called at compile-time are memoized, they should be pure function.
But it seems this is promised by another mechanism: type valued expression must be comptime expression(raise "unable to evaluate constant expression" if any non-comptime expression is used) + there is no way to make a global comptime var(mutable).
But there is a "counterexample":
const std = #import("std");
const expect = std.testing.expect;
test {
comptime var x: comptime_int = undefined;
const ns = struct {
fn foo() type {
return struct {
const v: i32 = x;
};
}
};
x = 10;
const a = ns.foo();
x = 20;
const b = ns.foo();
try expect(a == b);
try expect(a.v == 20);
try expect(b.v == 20);
}
But if the first access of v is before x = 20, the a.v and b.v will be 10.
const std = #import("std");
const expect = std.testing.expect;
test {
comptime var x: comptime_int = undefined;
const ns = struct {
fn foo() type {
return struct {
const v: i32 = x;
};
}
};
x = 10;
const a = ns.foo();
try expect(a.v == 10);
x = 20;
const b = ns.foo();
try expect(a == b);
try expect(a.v == 10);
}

Related

Dart store prime numbers in array

May I know how to store the N prime numbers, which I got from for loop in an array in dart?
import 'dart:io';
void main() {
// print('enter a start number');
// int a = int.parse(stdin.readLineSync()!);
print('enter a number');
int b = int.parse(stdin.readLineSync());
print('this are prime numbers');
primenum(b);
var z = '';
}
primenum(b) {
String string = "";
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
var z = i.toString();
// print(z);
var h = z;
// String str = '';
string = string + h;
}
List d = string.split('');
print(d);
}
Using the above code, I am able to get those numbers in List. But the double-digit numbers are splitting.
May I know How to solve the above task? using dart.
The way you're doing string.split is splitting the string into a list of each individual character. Instead, you can add each prime number to a List directly without doing string manipulation.
primenum(b) {
List<String> d;
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
d.add(i.toString());
}
print(d);
}

Dart error, This constructor should initialize field 'x' because its type 'int' doesn't allow null

I'm new to Dart. This is my code:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) {
x = i;
y = i;
}
}
main() {}
I got this error when running it.
bin/dart1.dart:7:3: Error: This constructor should initialize field 'x' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:2:7: Context: 'x' is defined here.
int x;
^
bin/dart1.dart:7:3: Error: This constructor should initialize field 'y' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:3:7: Context: 'y' is defined here.
int y;
^
As I understand, the parameter int i of Point.same() is non-nullable, and I use it to initialize x and y (x = i; y = i;). Why it still asks me to initialize x and y? I even tried the following code and still got the same error:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same() {
x = 3;
y = 3;
}
}
main() {}
When initializing fields from a constructor without constructor parameters, use the initializer list. It runs prior to the constructor body and allow you to initialize final and non-nullable variables without marking them late.
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) :
x = i,
y = i;
}
main() {}

Function to find the duplicate characters in a string with their number of occurrences in the Dart language

How can we find duplicate characters in a string with their number of occurrences? The function should be generic in the Dart language.
Sample:
Input = “abcBCAacd”
Output = “a”: 3
“B” : 2 , “c” :3
void main(List<String> args) {
var input = 'abcBCAacd'.toLowerCase().split('');
var list1 = input.toSet();
var myMap = Map<String, int>.fromIterables(list1, List.generate(list1.length, (i) => 0));
input.forEach((e) => myMap[e] = myMap[e]! + 1);
print(myMap);
}
Result:
{a: 3, b: 2, c: 3, d: 1}
I had to presume you wanted the d counted, and that everything should be folded to lowercase. If B and b are in different buckets, just remove the toLowerCase() from below:
void main() {
var input = 'abcBCAacd';
var chars = input.toLowerCase().split('');
var counts = <String, int>{};
for (var char in chars) {
counts[char] = (counts[char] ?? 0) + 1;
}
print(counts);
}
void main() {
int nbOccurence = 0;
String input ="abcdeffff";
for( var i = 0 ; i < input.length; i++ ) {
nbOccurence = 0;
for( var j = 0 ; j < input.length; j++ ) {
if (input[i] == input[j]){
nbOccurence++;
}
}
print(input[i] + ":" + nbOccurence.toString());
}
}

BinaryOperator doesn't work when comes to a=function(b,c)?

I want to identify the Expression like int a = function(b,c), so I wrote the code as followers:
void foo(int* a, int *b) {
int x;
int m;
int z;
int *p;
if (a[0] > 1) {
b[0] = 2;
z=10;
x = function( sizeof(char));
}
m = function( sizeof(char));
bar(x,m);
}
void bar(float x, float y);
int function(int size){
return size;
}
And than I used clang -Xclang -ast-dump -fsyntax-only cfunc_with_if.c to get the AST of the code:
From the result I found the AST Node type of int a = function(b,c) is BinaryOperator. In order to verify this, I use VisitStmt(Stmt *s) to print out all stmts' type.
bool VisitStmt(Stmt *s) {
if(isa<Stmt>(s)) {
Stmt *Statement = dyn_cast<Stmt>(s);
//Statement->dump();
std::string st(Statement->getStmtClassName());
st = st + "\n";
TheRewriter.InsertText(Statement->getLocStart(), st, true, true);
}
return true;
}
But the result is so weird. There is nothing printed out about the type of int a = function(b,c). and I'm so confused about the result. Is there some error in my code or something else?
There's no output at bar(x,m); either. Are there any errors when the tool compiles the code being analyzed? As written above, the code would fail to compile at x = function( sizeof(char)); since function has not been declared. Even when compilation has failed due to errors, the libtool tools can still run at least partially, with strange results.
Edit to add: what happens if you run the tool on this code?
void bar(float x, float y);
int function(int size);
void foo(int* a, int *b) {
int x;
int m;
int z;
int *p;
if (a[0] > 1) {
b[0] = 2;
z=10;
x = function( sizeof(char));
}
m = function( sizeof(char));
bar(x,m);
}
void bar(float x, float y);
int function(int size){
return size;
}

string.find failed on Chinese character in Android but success on PC when developing cocos-lua game

I try to use string.find("中国", "中"). It successed on PC but failed on Android when I develop my cocos-lua game.
on Android, string.find return nil
Fristly, I think their encoding may be diffent, so I try to print out their byte.
on Android: text1: "中国", text2:"中".
local text1 = self.__editBox2:getText()
local text2 = self.__editBox3:getText()
local code1 = ""
for i = 1, string.len(text1) do
code1 = code1 .. "-" .. tostring(string.byte(text1, i))
end
local code2 = ""
for i = 1, string.len(text2) do
code2 = code2 .. "-" .. tostring(string.byte(text1, i))
end
self.__editBox2:setText(code1)
self.__editBox3:setText(code2)
local a, b = string.find(text1, text2)
local data = tostring(a) .. ":" .. tostring(b)
self.__editBox1:setText(data)
text1:
228-184-173-229-155-189
text2:
228-184-173
The Answer is still:
nil:nil
PS: lua implementation of string.find
static int str_find_aux (lua_State *L, int find) {
size_t l1, l2;
const char *s = luaL_checklstring(L, 1, &l1);
const char *p = luaL_checklstring(L, 2, &l2);
ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
if (init < 0) init = 0;
else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
if (find && (lua_toboolean(L, 4) || /* explicit request? */
strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
/* do a plain search */
const char *s2 = lmemfind(s+init, l1-init, p, l2);
if (s2) {
lua_pushinteger(L, s2-s+1);
lua_pushinteger(L, s2-s+l2);
return 2;
}
}
else {
MatchState ms;
int anchor = (*p == '^') ? (p++, 1) : 0;
const char *s1=s+init;
ms.L = L;
ms.src_init = s;
ms.src_end = s+l1;
do {
const char *res;
ms.level = 0;
if ((res=match(&ms, s1, p)) != NULL) {
if (find) {
lua_pushinteger(L, s1-s+1); /* start */
lua_pushinteger(L, res-s); /* end */
return push_captures(&ms, NULL, 0) + 2;
}
else
return push_captures(&ms, s1, res);
}
} while (s1++ < ms.src_end && !anchor);
}
lua_pushnil(L); /* not found */
return 1;
}
static int str_find (lua_State *L) {
return str_find_aux(L, 1);
}
Lua does not have proper support to unicode characters out of the box, but there are good libraries that will fix that. I have never used cocos2d and I'm unsure if they have any add-ons to deal with this. But you could try using this one:https://luarocks.org/modules/xavier-wang/luautf8. I have used it with success once. Hope this helps!

Resources