OCaml: Core.Univ usage example - ocaml

So I have been looking at Core.Univ as a way of constructing heterogeneous arrays.
Suppose I do
let int_type = Core.Type_equal.Id.create ~name:"" Sexplib.Conv.sexp_of_int;;
let int_type' = Core.Type_equal.Id.create ~name:"" Sexplib.Conv.sexp_of_int;;
let i = Core_kernel.Univ.create int_type 5;;
let j = Core_kernel.Univ.create int_type' 5;;
When I do
Core_kernel.Univ.match_ i int_type'
It doesn't match as expected since the documentation for Type_equal.Id says that two calls to create with the exact same arguments will result in two distinct identifiers.
Does this mean that the API user is responsible for ensuring that only one instance of Type_equal.Id exists for each type?

Yes. I'd say that Core's terminology is a little bit unfortunate here.
Remember that once you compiled your program, at runtime there are (almost) no types in OCaml (see e.g. here or here for more information).
This means there's no way to introspect the values returned by Core.Type_equal.Id.create to detect for which type they really are and hence no way to detect if you already invoked create for an existing identical type (which would allow to return an already created identifier).
Rather than identifiers for types you should rather see these values as typed key identifiers. By controlling who has access to these key identifiers trough the module system you can control in a type safe way who can access the contents of universal values that were created with them.

Related

Can list cast correctly in Kotlin?

I am new to Kotlin,
data class RewardDetail(
val name: String
val isActivated: Boolean
val amountInCents: Int?
val Campain: String?
val expirationDate: Long?
)
class Rewards(Array<Reward>)
class Reward(
    val name: String
   
isActive: Boolean
   
amountInCents: Int
    campaignId: String
    expirationDate: LocalDateTime
)
val details : List<RewardDetail> = blablabla
val rewards = Rewards(details)
can details cast to rewards successfully?
Also note campaignId and Campain field name are different in RewardDetail and Reward and some fields can be nullable in RewardsDetail
What is the best way to handle situation like this?
Kotlin is strongly-typed. You can never successfully cast one thing into a different class. You can only cast an object into a type that it already satisfies. For example, if you have an Int that is currently only known to the compiler to be a Number, you can cast to Int to tell the compiler that it has an Int, so the compiler will allow you to use the functions that are specific to Int. But nothing but an Int can ever be cast to an Int.
So, unlike weakly typed languages, casting does not convert from one type to another. Casting is only you making a promise to the compiler that an object already is of the other type.
In your example, the only way to get a RewardDetail from a Reward is by writing a function that manually converts each property to the appropriate type.
The Rewards class above is largely redundant. There's no need for a wrapper class around a single Array or List unless you need to do validation of items added to or retrieved from the list. In that case, it would probably make more sense to create a subclass of ArrayList for that purpose, so you could still easily iterate the list and use all the List and Iterable helper functions on it.
Probably about 95% of the time, you should prefer using List over using Array. Arrays should be used only when you need a fixed size collection that is also mutable, or if you are working with highly performance-critical code. The reason it should be limited to these uses is that mutability should be avoided when possible for robustness and Arrays are more cumbersome to work with than MutableLists.
A typical implementation of a function that converts from one type to another would be to write an extension function RewardDetail.toReward() extension function, or a toReward() function inside the RewardDetail class. However, in your case you need to decide what you need to happen when some of the values of RewardDetail are null. Maybe you just return null so your conversion function should be toRewardOrNull(), or you provide default values for the properties that have no value in RewardDetail.

How to automatically initialize component parameters?

While doing a game engine that uses .lua files in order to read parameter values, I got stuck when I had to read these values and assign them to the parameters of each component in C++. I tried to investigate the way Unity does it, but I didn't find it (and I'm starting to doubt that Unity has to do it at all).
I want the parameters to be initialized automatically, without the user having to do the process of
myComponentParameter = readFromLuaFile("myParameterName")
for each one of the parameters.
My initial idea is to use the std::variant type, and storing an array of variants in order to read them automatically. My problems with this are:
First of all, I don't know how to know the type that std::variant is storing at the moment (tried with std::variant::type, but it didn't work for the template), in order to cast from the untyped .lua value to the C++ value. For reference, my component initialization looks like this:
bool init(luabridge::LuaRef parameterTable)
{
myIntParameter = readVariable<int>(parameterTable, "myIntParameter");
myStringParameter = readVariable<std::string>(parameterTable, "myStringParameter");
return true;
}
(readVariable function is already written in this question, in case you're curious)
The second problem is that the user would have to write std::get(myIntParameter); whenever they want to access to the value stored by the variant, and that sounds like something worse than making the user read the parameter value.
The third problem is that I can't create an array of std::variant<any type>, which is what I would like to do in order to automatically initialize the parameters.
Is there any good solution for this kind of situation where I want the init function to not be necessary, and the user doesn't need to manually set up the parameter values?
Thanks in advance.
Let's expand my comment. In a nutshell, you need to get from
"I have some things entered by the user in some file"
to:
"the client code can read the value without std::get"
…which roughly translates to:
"input validation was done, and values are ready for direct use."
…which implies you do not store your variables in variants.
In the end it is a design question. One module somewhere must have the knowledge of which variable names exist, and the type of each, and the valid values.
The input of that module will be unverified values.
The output of the module will probably be some regular c++ struct.
And the body of that module will likely have a bunch of those:
config.foo = readVariable<int>("foo");
config.bar = readVariable<std::string>("bar");
// you also want to validate values there - all ints may not be valid values for foo,
// maybe bar must follow some specific rules, etc
assuming somewhere else it was defined as:
struct Configuration {
int fooVariable;
std::string bar;
};
Where that module lives depends on your application. If all expected types are known, there is no reason to ever use a variant, just parse right away.
You would read to variants if some things do not make sense until later. For instance if you want to read configuration values that will be used by plugins, so you cannot make sense of them yet.
(actually even then simply re-parsing the file later, or just saving values as text for later parsing would work)

Looking for construct simto VB's WITH statement

Updating some archaic F77 that no longer fully supported our needs. I am looking for the functional equivalent of VB's "WITH" statement to support the conversion from a mass of F77 disconnected, individual variables to hierarchical derived Types. While the code is much easier to read and understand the downside is that the code becomes very cumbersome and prone to typos. So, the use of WITH would greatly ease the conversion burden.
VB's "WITH" statement executes a series of statements on a single object or a user-defined type.
Example:
if I want to reference elements my derived Type named Loads I would write code with Loads% prefixing each element and that is cumbersome. The WITH statement allows one to re-write the block with an assumed reference to Loads%.
WITH Loads%
ID = blah
Description = blahblah
Duty(I) = 2
End WITH
Suggestions...?
There's no Fortran construct which provides a precise analog to what you describe as VB's with statement. For your particular example, you could write something along the lines of ...
Given a derived type definition such as
type :: load
character(4) :: id
character(32) :: description
integer, dimension(4) :: duties
end type load
and a variable of that type
type(load) :: loads
you can use a default constructor to set the values of the members of loads, like this:
loads = load('myid', 'my description', [1,2,3,4])
or even like this:
loads = load(duties=[3,4,5,6], id = 'id2', description='description')
If you look around on SO for Qs and As on the subject of Fortran derived type constructor you'll find out how to build more complicated constructors which don't need all the members to be given values when they are called. There are some useful resources elsewhere on the internet too.
If one of your concerns is to avoid typing long, and possibly multipart, entity names then the associate construct might help. For example, if, rather than loads the name of the variable you wanted to avoid typing was something like long%structured%entity you might write
associate (shnm => long%structured%entity`)
shnm%id = 'idxx'
*etc*
end associate
I'm sure you could easily come up with more extensive examples of the use of with which would not be easy to translate to Fortran without repeated writing of loads%.

Lua: how to verify that a table contains a specific function

I'm developing a module that returns a table full of functions based on the arguments that are passed in. Specifically, the module returns a set of data transformation rules (functions) that need to be applied to a data set depending on which customer is sending it.
I decided to decouple my rule library (biz logic) from the code that decides which of the rules should be applied (config logic).
Here's the unit test I'm writing to verify that the ruleBuilder is adding the correct rule (function) based on one of my scenarios:
ruleBuilder = require("ruleBuilder")
ruleLibrary = require("ruleLibrary")
local rules = ruleBuilder.assembleRules("Customer1231")
assert(rules[1] == ruleLibrary.missingSSNRule)
Is this the correct way to do that verification? Will this work even if the ruleLibrary.missingSSNRule function has references to several other functions via a closure or parameter?
To verify that a table contains a particular function you may use the fact that keys in Lua tables can be anything (including functions). In your assembleRules code you can write something like this:
function assembleRules(...)
...
return {
[someOtherCoolModule.coolFunction] = someOtherCoolModule.coolFunction,
[yetAnotherModule.anotherFunction] = yetAnotherModule.anotherFunction,
}
end
Then later you can simply check if the key exists:
local rules = ruleBuilder.assembleRules("somedata")
assert(rules[someOtherCoolModule.coolFunction])
On the assumption that the return value of ruleBuilder.assembleRules is supposed to somehow know to put someOtherCoolModule.coolFunction in the 0-th index (note: Lua uses 1-based indices. Don't use 0 as an index) of its return value, then yes.
Will this work even if someOtherCoolModule.coolFunction is a closure?
All functions in Lua are closures. However, I'm going to assume that you mean that ruleBuilder.assembleRules is going to take someOtherCoolModule.coolFunction and build a new function around it.
A function is equal to itself. But it is only equal to itself. Just like two tables are only equal if they are the same table object, two functions are only equal if they are the same function. Functions are not equal to a different instantiation of the same function, nor is it equal to any other function. Here are examples of this.

C++ Get a function pointer or eval a function using the functions name stored in a string

I am working on a parser for natural language. Words from natural language are parsed to the concepts that they represent. The purpose is to allow a robot to interpret commands given in natural language. One way to execute these commands would be by creating an enormous amount of if statements, which would turn into at east one for each concept. I was wondering if there was a way to retrieve a function pointer to a function whose name is stored as string. Each concept could then contain a string that represented the function that would need to executed if the concept is present in the parse. This way the concept would already know what to do.
This is not so complicated. I would try to (theoretically, of course) implement one of these "possible" solutions:
This is very C++: Read Instantiate class from name? and create a class for each of the "natural" language, make sure that these classes derive from a common interface, and each of the classes would have the overridden method would handle the specific word.
This is more C: In case you are not afraid to use shared libraries, create a shared library, with all the functions for the commands you want, make sure the functions name match the "words" and then just load the specific function (word) you want to use. This is even easier than the one above, since you don't need to know all the words, and there is less maintenance.
Cheers