Is it possible to define a function that returns an object of unknown shape, so that it would allow returning something like
let basic = {
example = 0.0;
another = 2.2;
third = {
a = {
b = 2;
c = 3;};
b = 2;}
};
but also something like
let just_one = {
onething = "true";
};
What’s the syntax for that?:
public func returnObjectOfUnknownShape(arg1: Text) : [what goes here?] {
Or should I be using some other type for this kind of structured data? Which one?
1 Like
You can use a variant:
type MyVariant = {
#basic : {
example : Float;
another : Float;
third : {
a : {
b : Nat;
c : Nat;
};
b : Nat;
};
};
#onething : Text;
};
func returnObjectOfUnknownShape(arg1: Text) : MyVariant {
if (arg1 == "") {
#basic {
example = 0.0;
another = 2.2;
third = {
a = {
b = 2;
c = 3;
};
b = 2;
}
}
} else {
#onething "true"
}
};
My talk from Motoko Bootcamp might help gain an intuition for them:
1 Like
For it to be truly unknown you’d need to use a type argument, but that means the only useful thing you can do with the value is return it:
func returnObjectOfUnknownShape<T>(arg1: T) : T {
arg1
};
This is more commonly known as the “identity” function:
func id<A>(x: A) : A = x;
let basic = {
example = 0.0;
another = 2.2;
third = {
a = {
b = 2;
c = 3;
};
b = 2;}
};
let just_one = {
onething = "true";
};
let _ = id(basic);
let _ = id(just_one);
2 Likes
Thank you. I did see this at the time and forgot to reply.
I was trying to make it return an object of unknown shape, having done some processing on it, which appears to be impossible in Motoko. It’s ok.
You can do this:
func returnObjectOfUnknownShape(arg1: Text) : {} {
if (arg1 == "") {
{
basic = {
example = 0.0;
another = 2.2;
third = {
a = {
b = 2;
c = 3;
};
b = 2;
};
};
};
} else {
{
just_one = "true";
}
}
};