Generation of types in zig (zig language) - zig

Is it possible to create a comptime function in zig that would generate a new struct type? The function would receive an array of strings and an array of types. The strings are the names of subsequent struct fields.

This has been implemented now as https://github.com/ziglang/zig/pull/6099
const builtin = #import("std").builtin;
const A = #Type(.{
.Struct = .{
.layout = .Auto,
.fields = &[_]builtin.TypeInfo.StructField{
.{ .name = "one", .field_type = i32, .default_value = null, .is_comptime = false, .alignment = 0 },
},
.decls = &[_]builtin.TypeInfo.Declaration{},
.is_tuple = false,
},
});
test "" {
const a: A = .{ .one = 25 };
}
The TypeInfo struct is defined here.

Partially. This has been long proposed at https://github.com/ziglang/zig/issues/383
You can only do so with fields, not with custom decls.

Related

why do user defined types in zig need to be const?

In case I need to declare a struct in Zig I have to prefix it with a const
const Arith = struct {
x: i32,
y: i32,
fn add(self: *Arith) i32 {
return self.x + self.y;
}
};
test "struct test" {
var testArith = Arith{
.x = 9,
.y = 9,
};
expect(testArith.add() == 18);
}
But it can be initialized both ways as var and const so why does the type declaration need a constant keyword when it only matters whether the instance of the struct is const or not?
Need to be const because the order of evaluation in the root scope is undefined and because the variables of type type only can live in the compiler (has no memory representation, the compiler is unable to produce a binary representation of it). But you can use var inside other scopes:
comptime {
var T = struct { value: u64 };
const x: T = .{ .value = 3 };
T = struct { ok: bool };
const y: T = .{ .ok = true };
#compileLog(x.value); // <- 3
#compileLog(y.ok); // <- true
}
Run this code
In the rest of the answer, I explain in detail.
Const
const Arith = struct {...};
Creates a constant variable of a inferred type. In this case, the variable Arith has type type:
const Arith = struct {...};
comptime {
#compileLog(#TypeOf(Arith)); // <- type
}
Run this code
This is the same as declare the variable as:
const Arith: type = struct {...};
Var
You also can create a variable with var
Examples:
comptime {
var Arith = struct {...};
}
comptime {
var Arith: type = struct {...};
}
fn main() !void {
comptime var Arith = struct {...};
}
fn main() !void {
var Arith: type = struct {...};
}
fn main() !void {
comptime var Arith: type = struct {...};
}
Because is a variable you can modify it:
comptime {
var T = u64;
T = bool;
#compileLog(T); // <-- bool
}
Run this code
Comptime Types
There is types that can only live in the compiler, like: type or structs that have a field of type anytype or other comptime type.
In the case of type, this make the compiler interpret var x: type as comptime var x: type.
Then, consider the following code:
var T = struct { value: u64 }; // <- Compiler error
comptime {
const x: T = .{ .value = 3 };
}
error: variable of type 'type' must be constant
because the order of evaluation in the root scope is undefined, the compiler forces to create a global variable inside the binary, but the type type has no memory representation. So, the compiler raises an error.
Since Arith is of the type type it has to be declared a constant because the compiler expects it to be. This can be checked by changing the type declaration to this and running the program
var Arith = struct {
x: i32,
y: i32,
fn add(self: *Arith) i32 {
return self.x + self.y;
}
};
which will result in the error error: variable of type 'type' must be constant
Also in Zig we need either a const or a var preceeding a name otherwise it is considered an invalid token.

Splitting in Dart

How to Spilt this paymentUrl.
const _paymentUrl =
'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
TO Get
{Address: "3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra", Amount: "0.00107000"}
It looks like a URI, and is named like a URI, so try using the Uri class:
const _paymentUrl =
'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
var bcUri = Uri.parse(_paymentUrl);
var address = bcUri.path;
var amount = bcUri.queryParameters["amount"];
var map = {"Address": address, "Amount": amount};
it seems the ? is always there, so you can split it based on it like this:
const _paymentUrl = 'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
List<String> splitPayment = _paymentUrl.split('?');
String bitcoin = splitPayment[0];
String amount = splitPayment[1];

How can I sort a class using an array? - swift 5

I've a class called "cars":
car1 = [name: "ferrari", color: "black", size: "small" ]
car2 = [name: "Lamborghini", color: "orange", size: "small" ]
car3 = [name: "Audi", color: "black", size: "big" ]
car4 = [name: "fiat", color: "yellow", size: "small" ]
car5 = [name: "ferrari", color: "red", size: "medium" ]
and made a list of them:
list = [car1,car2,car3,car4]
and now I want to sort/filter this list.
If I try filtering it using a string, everything works fine:
let searchtext = "Audi"
filteredlist = list.filter({ $0.name.lowercased().contains(searchText.lowercased()) })
--> filteredlist = [car3] //result
but I want to use an array, so them I could have more results shown. Something like filtering by more than one color (similar to an "or" condition in an "if statement").
I've tried the same struct (but of course didn't work):
let searchtext = ["black","red"]
filteredlist = list.filter({ $0.color.contains(searchText) })
--> filteredlist = [car1,car3,car5] //expected, got compilation error instead
I'm having these errors:
Cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
Instance method 'contains' requires that '[String]' conform to 'StringProtocol'
I can think in 2 solutions (that aren't the ideal ones) to solve this need:
1 - create a while/for function and filter the list for each element of the searchtext array and unite everything in the end (not recommended because I will have to read the list 'n' times )
update:stupid way
var i = 0
var listapp: [Item] = []
while i < searchtext.count {
listapp.append(contentsOf: list.filter({ $0.tipo.contains(searchtext[i]) }))
i += 1
}
list = listapp
2 - manually filtering the list using 'if','or','while' instead of using list.filter function
The other way round:
let searchtext = ["black","red"]
filteredlist = list.filter({ searchtext.contains($0.color) })
A double contains should do it:
let searchText = ["black", "red"].map { $0.lowercased() }
filteredlist = list.filter { item in
let color = item.color.lowercased()
return searchText.contains { text in color.contains(text) }
}

Highcharts : categories in format with double quotes

I have series in the javascript using below code. Getting correct values but it is in Double quotes. So that is the reason I am not getting drilled down chart.
var arrayCodeSeries = <%= serializer.Serialize(ViewData["arrayCodeSeries"]) %>;
i = 0;
for(i=0;i<arrayCodeSeries.length;i++)
{
var temp = arrayCodeSeries[i];
temp = '['.concat(temp,']');
arrayCodeSeries[i] = temp;
}
I am getting
arrayCodeSeries[0] = "['70-158','70-177','70-181']"
data = [{
y: parseInt(arrayTotalCertificateCount[0]),
color: colors[0],
drilldown: {
name: 'Certificate Code',
categories: arrayCodeSeries[0],
data: [2,2,1],
color: colors[0]
}
I tried to remove double quotes with Replace, ReplaceAll and substring functions but it gets me error like it doesn't support these functions.
Help...
Thank you..
attaching here the array :
JS Fiddle with Static data http://jsfiddle.net/xj6ms/1/
According to comment discussion:
You should change your code from:
for(i=0;i<arrayCodeSeries.length;i++) {
var temp = arrayCodeSeries[i];
temp = '['.concat(temp,']');
arrayCodeSeries[i] = temp;
}
to:
var temp = [];
for(i=0;i<arrayCodeSeries.length;i++) {
var items = arrayCodeSeries[i].split(',');
temp.push(items);
}

giving input to highchart using JSON

i'm new to highchart
using a default JSON value given by highchart team wrks fine here is the link
default high chart values
but however when i try to give input as JSON as a local variable shows nothing in the graph, here is the code
var myval = new Array();
myval [0] = "1146096000000,69.36";
myval [1] = "1146182400000,70.39";
myval [2] = "1146441600000,69.60";
/******* OR ******/
//var myval = [ [1146096000000,69.36], [1146182400000,70.39], [1146441600000,69.60]];
/***** DOESN'T WORk *****/
var obj = jQuery.parseJSON ( myval );
$.getJSON(obj, function(data) {
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 2
},
title : {
text : 'value graph'
},
series : [{
name : 'val 1',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
If you define myVal as:
var myVal = [ [1146096000000,69.36], [1146182400000,70.39], [1146441600000,69.60]];
then it is already json, and doesn't need to be parsed using parseJSON. You can simply set
data = myVal;
If myVal is defined as
var myval = new Array();
myval [0] = "1146096000000,69.36";
myval [1] = "1146182400000,70.39";
myval [2] = "1146441600000,69.60";
Then myval is a json object containing strings. You can either parse out each elemnt of the array (e.g. using split) or define it like this:
var myval = new Array();
myval [0] = [1146096000000,69.36];
myval [1] = [1146182400000,70.39];
myval [2] = [1146441600000,69.60];
in which case, it is also already a json object and won't need to be parsed.
The only time you need to parse JSON is if the original data is a string representation of a json object, e.g. when getting the data from an ajax call.

Resources