Calling GMP from Zig - zig

I'm new to Zig and wanted to use the cImport to call out to the GNU Multiprecision library GMP. I got this to work but it feels awkward because Zig apparently doesn't cast from arrays to pointers by default and GMP uses this approach to pass by reference. Is there a cleaner approach than mine? Are there existing examples of Zig calling GMP?
const gmp = #cImport({
#cInclude("gmp.h");
});
pub fn main() void {
var x: gmp.mpz_t = undefined;
gmp.mpz_init(&x[0]);
gmp.mpz_set_ui(&x[0], 7);
gmp.mpz_mul(&x[0], &x[0], &x[0]);
_ = gmp.gmp_printf("%Zd\n", x);
}

You should be able to drop the [0]:
const gmp = #cImport({
#cInclude("gmp.h");
});
pub fn main() void {
var x: gmp.mpz_t = undefined;
gmp.mpz_init(&x);
gmp.mpz_set_ui(&x, 7);
gmp.mpz_mul(&x, &x, &x);
_ = gmp.gmp_printf("%Zd\n", x);
}

Related

Declaring pointer to function

I found some (a bit strange) feature of zig when played with function pointers.
Here is an example which I beleive is written as implied.
const std = #import("std");
const print = std.debug.print;
const aFunc = fn (x: i32) void;
fn theFunc(x: i32) void {
print("have {}\n", .{x});
}
pub fn main() void {
const f: aFunc = theFunc;
f(3);
}
This code compiles and runs Ok.
Now change it like this.
const std = #import("std");
const print = std.debug.print;
const aFunc = fn someFunc (x: i32) void;
fn theFunc(x: i32) void {
print("have {}\n", .{x});
}
pub fn main() void {
const f: aFunc = theFunc;
f(3);
}
This code is also Ok, but shouldn't the compiler emit error/warning about someFunc?
This name is useless - when I tried to use it instead of aFunc there was an compilation error.
Compiler version:
$ /opt/zig/zig version
0.10.0-dev.3431+4a4f3c50c
It looks like the zig source parser treats
const aFunc = fn someFunc (x: i32) void;
as if it is function definition, but silently drops someFunc.

Does Zig support the union of anonymous structs and arrays?

Is this possible in zig? And if so how would something like the following C++ code look in Zig?
template<class T>
class vec3
{
union
{
struct{ T x,y,z; };
T vec_array[3];
};
};
No, there is no such thing supported in Zig, and it is unlikely there ever will be. The closest you'll get is something like this:
const std = #import("std");
pub fn Vec3(comptime T: type) type {
return extern union {
xyz: extern struct { x: T, y: T, z: T },
arr: [3]T,
};
}
test {
var v3: Vec3(u32) = .{ .arr = .{ 42, 73, 95 } };
try std.testing.expectEqual(v3.arr[0], v3.xyz.x);
try std.testing.expectEqual(v3.arr[1], v3.xyz.y);
try std.testing.expectEqual(v3.arr[2], v3.xyz.z);
}
where the extern qualifiers here make the containers behave in accordance with the C ABI (and in the case of the union, makes it defined behavior to access any member).
See this comment under proposal #985 for a fairly comprehensive rationale on as to why "anonymous field nesting" was rejected.

Idiomatic way to wite/pass type to generic function in ziglang

This is a much simplified version of my real issue but hopefully demonstrates my question in a concise manner.
My question is about the interface to printKeys. I have to pass in the type of the data to be printed as a comptime parameter, and the easiest way to get this is to use #TypeOf on the map at the point of calling it.
Coming from C++ this seems slightly inelegant that the type can't be inferred, although I do like being explicit too.
Is there a more idiomatic way to have a generic function in zig that doesn't need this use of #TypeOf at the point of calling, or a better way to do this in general?
const std = #import("std");
fn printKeys(comptime MapType: type, data: MapType) void {
var iter = data.keyIterator();
while (iter.next()) | value | {
std.debug.print("Value is {}\n", .{value.*});
}
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
var map = std.AutoHashMap(i32, []const u8).init(allocator);
defer map.deinit();
try map.put(10, "ten");
try map.put(12, "twelve");
try map.put(5, "five");
printKeys(#TypeOf(map), map);
}
use anytype. you can find more examples in zig docs (Ctrl + F) and search anytype
fn printKeys(data: anytype) void {
...
}
pub fn main() !void {
...
printKeys(map);
}

Could you demo a very simple C++ example about Symbolic variable and Jacobian by converting Pydrake code to C++ version?

I am trying to convert the following pydrake code to C++ version. Unfortunately,I get lost in the very rigorous C++ API documentation. Could you help to convert the following code into C++ version for a tutorial? Thank you so much!
import pydrake.math as drake_math
import pydrake.symbolic as sym
def cost_stage(x):
m = sym if x.dtype == object else np # Check type for autodiff
cost = m.sqrt(x[0]**2 + x[1]**2 )
return cost
x_sym = np.array([sym.Variable("x_{}".format(i)) for i in range(n_x)])
x = x_sym
l = cost_stage(x)
self.l_x = sym.Jacobian([l], x).ravel()
Since you used the name "cost", I suppose you want to use this as a cost in drake's MathematicalProgram, so I created MyCost class which can be used in Drake's MathematicalProgram. If you don't want to use MathematicalProgram later, you could just use the templated function DoEvalGeneric only without the class MyCost.
Here is the C++ pseudo-code (I didn't compile or run the code, so it is highly likely there are bugs in the code, but you get the idea)
#include "drake/solvers/cost.h"
#include "drake/common/symbolic.h"
class MyCost : public drake::solvers::Cost {
public:
MyCost() {}
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override {
DoEvalGeneric<double>(x, y);
}
void DoEval(const Eigen::Ref<const drake::AutoDiffVecXd>& x, drake::AutoDiffVecXd* y) const override {
DoEvalGeneric<drake::AutoDiffXd>(x, y)
}
void DoEval(const Eigen::Ref<const drake::VectorX<drake::symbolic::Variable>>& x, drake::VectorX<drake::symbolic::Expression>* y) const override {
DoEvalGeneric<drake::symbolic::Expression>(x.cast<drake::symbolic::Expression>(), y);
}
private:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const drake::VectorX<T>>& x, drake::VectorX<T>* y) const {
y->resize(1);
using std::sqrt
(*y)(0) = sqrt(x[0] * x[0] + x[1] * x[1]);
}
};
void main() {
const drake::symbolic::Variable x0{"x0"};
const drake::symbolic::Variable x1{"x1"};
drake::Vector2<drake::symbolic::Variable> x(x0, x1);
MyCost cost{};
drake::VectorX<drake::symbolic::Expression> y;
cost.Eval(x, &y);
std::cout << y(0).Jacobian(x) << "\n";
}
Here I created a templated function DoEvalGeneirc to handle the three different scalar types double, AutoDiffXd and symbolic expression. You could see similar patterns in the drake codebase https://github.com/RobotLocomotion/drake/blob/6ee5e9325821277a62bd5cd5456ccf02ca25dab7/solvers/cost.cc#L14-L33
If you don't need to use cost in drake MathematicalProgram, then you can create your cost function in C++ as
#include "drake/common/symbolic.h"
#include <Eigen/Core>
template <typename Derived>
typename Derived::Scalar cost_stage(const Derived& x) {
using std::sqrt;
return sqrt(x[0] * x[0] + x[1] * x[1]);
}
int main() {
const drake::symbolic::Variable x0{"x0"};
const drake::symbolic::Variable x1{"x1"};
drake::Vector2<drake::symbolic::Variable> x(x0, x1);
const drake::symbolic::Expression l = cost_stage(x.cast<drake::symbolic::Expression>());
std::cout << l.Jacobian(x) << "\n";
return 0;
}
Then you can call Jacobian on the return argument of cost_stage.

Dart type safety for map key, not working?

With the following trivial dart function:
void main()
{
Map<String, dynamic> m = { 2 : 200.0, 'x' : 8.0 };
print( "m: $m");
}
Why doesn't the Dart Editor / compiler complain about the int key type (2)? I would like some safetly that all of my key types are String's, but this seems to run fine.
This seems to be a bug. Editor and VM don't complain, despite the runtime type being int.
But you can use a workaround until this is fixed:
void main() {
Map<String, dynamic> m = {};
m[2] = 200.0; // editor complains here. VM in checked mode still works, for some reason.
m['x'] = 8.0;
}

Resources