Declare type of struct field to be the same type as the struct itself in Julia
If I define a struct in Julia, is it possible to declare the type of one of its fields to be of the same type as the struct itself? For example, I want to define a struct NodeStruct
with two fields, data
and next
where data
is some standard type (e.g. AbstractFloat
) and next
is NodeStruct
type or nothing
. Consider this example code which gives an error LoadError: UndefVarError: NodeStruct not defined
.
import Base.@kwdef
@kwdef mutable struct NodeStruct{A<:AbstractFloat, B<:Union{NodeStruct, Nothing}}
data ::A
next ::B
end
Is it possible to do this somehow? I would like to be able to do this parametrically as the performance tips suggest this and computation time is very important to me. I could not find any information in the documentation on types or constructors that resolves this issue.
Thank you for reading and I would appreciate any advice that you might have.
1 answer
-
answered 2021-02-22 22:49
Przemyslaw Szufel
Since you know that elements of your structure a concrete type this just will be:
@kwdef mutable struct NodeStruct{A<:AbstractFloat} data ::A next ::Union{NodeStruct, Nothing} end
And now you just use it
julia> NodeStruct(3.5, nothing) NodeStruct{Float64}(3.5, nothing)
If you need slightly more abstract structure you can do:
abstract type AbstractNS end @kwdef mutable struct NodeStruct2{A<:AbstractFloat, B<:AbstractNS} <: AbstractNS data ::A next ::Union{Nothing, B} end
When creating the root for this abstract structure you need to provide the type:
julia> root = NodeStruct2{Float64, NodeStruct2}(3.5, nothing) NodeStruct2{Float64, NodeStruct2}(3.5, nothing)
However for leaves it will just work:
julia> leaf = NodeStruct2(5.6, root) NodeStruct2{Float64, NodeStruct2{Float64, NodeStruct2}}(5.6, NodeStruct2{Float64, NodeStruct2}(3.5, nothing))
See also questions close to this topic
-
How is exception handling implemented in Python?
This question asked for explanations of how exception handling is implemented under the hood in various languages but it did not receive any responses for Python.
I'm especially interested in Python because Python somehow "encourages" exception throwing and catching via the EAFP principle.
I've learned from other SO answers that a try/catch block is cheaper than an if/else statement if the exception is expected to be raised rarely, and that it's the call depth that's important because filling the stacktrace is expensive. This is probably principally true for all programming languages.
Are there any resources that explain how the Python exception handling was implemented internally and if special optimizations were made because of the EAFP principle?
-
Error-26499:InternalError-Invalid mptNetHandledTask=06C4BD90/ mptNetVUserVars=06CA2CEO/ptTaskItem=069659D0/ptVUserVars=05F0C040/ptSocket=00000000/meMa
Error-26499:InternalError-Invalid mptNetHandledTask=06C4BD90/ mptNetVUserVars=06CA2CEO/ptTaskItem=069659D0/ptVUserVars=05F0C040/ptSocket=00000000/meMaxTaskState=36=dummy_last_statein feProcessorSocket inLrwNetSocket.cpp
-
Most efficient way of finding dictionary values by (a larg list) of keys? Python 3.8
I have the following dictionary:
d = {"sadsa": 4, "awdwa" 13, ,"tdadq": 2 ...} composed of 100000 items
Now i have a list of around 1000 items: l = ["awdwa", "fdafs", ...]
What is the fastest way to retrieve all matching values?
Currently Im trying the following method:
- [d[i] for i in l if i in d]
Is there a faster way?
I read something about ordering, but im not sure what it means. Is it related to binary search?
How does the dictionary get value by key, works ... does it iterate through all keys until finding the matching one?
-
Cart is being reset back to zero once my function ends
Help Cart is being reset back to zero once my function ends.
My item is being created, and the fields populated. once my add item function runs it adds the item to the cart.cartItems array and increments the size. once the function ends the array is rest back to zero instead of having my recently added item. enter image description here
ShoppingCart AddItem(ItemToPurchase item, ShoppingCart cart){
if( cart.cartSize < MAX_CART_SIZE ){ cart.cartItems[cart.cartSize] = item; cart.cartSize++; } else{ printf("Cart it full, item can not be added\n"); } return cart;
-
Create an array of structs swift
struct Section { var date: Date var transactions: [Transaction] // array of my custom realm objects } @objcMembers class Transaction: Object { dynamic var id: String = UUID().uuidString dynamic var time: Int64 = 0 dynamic var details: String = "" // description dynamic var mcc: Int32 = 0 dynamic var hold: Bool = false dynamic var amount: Int64 = 0 dynamic var operationAmount: Int64 = 0 dynamic var currencyCode: Int32 = 0 dynamic var commissionRate: Int64 = 0 dynamic var cashbackAmount: Int64 = 0 dynamic var balance: Int64 = 0 dynamic var comment: String = "" dynamic var emoji: String = "❓" var sectionDict: [Section] = [] func convert(_ transactions: Results<Transaction>) -> [Section] { let section = Section(date: Date(), transactions: [Transaction()]) sectionDict.append(section) return sectionDict } let section = Section(date: Date(), transactions: [Transaction])
I get an error when trying to create an array of structs: Cannot convert value of type '[Transaction].Type' to expected argument type '[Transaction]'
Can't figure out what's the problem. As result i'm trying to store all my Transactions objects into let section arr.
-
Expression "passing by reference" for structs in C
I have recently had a class about structures in C and the lecturer used the expression "pass by reference" to describe the action of passing a pointer towards a structure to a function. I have always read that C does not have "pass by reference" because, unlike Cpp, pass by reference can only be emulated by passing by value a pointer towards some object — and we should rather say "pass by pointer". So I am wondering whether or not things work differently for structures and this expression is justified in this context.
-
Find the name of the Imported DLLs using PE Headers
A Few days back I have started with Windows System Programming using c++. Hence, thought of building a utility to grab the PE Headers of an exe file. And now I am stuck with the Image_Import_descriptor structure.
What I want is to get the names of the DLL files(modules) imported by the exe. And below is the code I am using to get those names:
DWORD Image_Import_Descriptor_addr = (DWORD)ntHeader + (DWORD)sizeof(ntHeader->FileHeader) + (DWORD)ntHeader->FileHeader.SizeOfOptionalHeader + (DWORD)ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; importImageDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)Image_Import_Descriptor_addr;
To get the RVA of the name:
DWORD name = importImageDescriptor->Name; printf("\n\n\n\t\t (((Module Name)): %X", name);
Gives an output: 4778B00
Hope untill now everything was fine technically.
However, my motive is to print the DLL names(like kernel32.dll). Can anyone help me out how to get the names of the DLL ?
My workarounds:
LPCSTR snames = (LPCSTR)name; printf("\n\n\n\t\t (((Module Name)): %s", *snames);
But this is giving me an error: Access Violation
I am getting confused with the pointers and Datatype conversions. A help is much appreciated.
-
When should TypeApplications be preferred over simple :: signatures or ScopedTypeVariables?
Considering this simple example of ambiguous type inference:
#! /usr/bin/env stack {- stack runghc -} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} main :: IO () main = do -- This will fail to compile without additional type info -- let w = read "22" -- print w -- My go-to for this is type signatures in the expressions let x = read "33" :: Integer print x -- Another possibility is ScopedtypeVariables let y :: Integer = read "44" print y -- How does TypeApplications differ from the code above? When should this be chosen instead? let z = read @Integer "55" print z
My question is, in cases like this, is there an advantage to using
TypeApplications
? -
Swift type erasure with property wrapper
Im struggling a little bit with the implementation of type-erasure in Swift.
I have a property wrapper
ThemeValue
which is a generic wrapper aroundTweakable
, in this caseString
orCGFloat
both conform toTweakable
What I am trying to achieve is to be able to get all the
ThemeValues
associated to the structI feel like I am fundamentally misunderstanding something here.
protocol Themeable { var tweakables: [ThemeValue<AnyTweakable>] { get } } extension Themeable { var tweakables: [ThemeValue<AnyTweakable>] // What I want to do is return all ThemeValues instance variables to this struct let themeValues = Mirror(respresenting: self).children.compactMap { // return $0.value as? ThemeValue<AnyTweakable> } } } struct ExampleThemeable: Themeable { let identifier: String = UUID().uuidString @ThemeValue<String>(key: "stringExample", defaultValue: "foo") public var stringExample @ThemeValue<CGFloat>(key: "floatExample", defaultValue: 0) public var floatExample }
enum TweakableType { case any case string case cgFloat } protocol Tweakable { var type: TweakableType { get } var stringValue: String { get } } extension String: Tweakable { var type: TweakableType { return .string } var stringValue: String { return self } } extension CGFloat: Tweakable { var type: TweakableType { return .cgFloat } var stringValue: String { return "\(self)" } } struct AnyTweakable: Tweakable { var type: TweakableType { return .any } var stringValue: String = "" } @propertyWrapper struct ThemeValue<T: Tweakable> { private let key: String let defaultValue: T var currentValue: T init(key: String, defaultValue: T) { self.key = key self.defaultValue = defaultValue self.currentValue = defaultValue } var wrappedValue: T { get { return currentValue } set { self.currentValue = newValue } } }
-
Julia: Writing a function "paramvalues" that returns a dictionary of parameter values
I am working on an Economics assignment and need to create a function in Julia that takes keyword arguments and returns them in the form of a dictionary. So far this is my code, but it is not running because there is "no method matching getindex(::Nothing, ::Symbol).
function paramvalues(a; Nb = 100, Ns = 100, Minval = 0, Maxval = 200, Mincost = 0, Maxcost = 200) d = Dict(:Nb => Nb, :Ns => Ns, :Minval => Minval, :Maxval => Maxval, :Mincost => Mincost, :Maxcost => Maxcost) for values in a d[values] = get(d, values, 0) end d end
-
Top level scope and bound errors in Julia
Hi all I have the following function. This is a function I made in Python that basically gives me an array of arrays, depending on which integer I feed to the function. The integer is basically the number of hexagons I include in my function.
function hex_index(N) x,y,z=0,0,0 count,mth_cell = 0,0 index_of_cells = [0,0,0] sixth = 1 while count <= N sixth = 1 mth_cell = 0 for i= 1:6*count if mth_cell==count mth_cell=0 sixth += 1 elseif sixth==2 x=0 y=count-mth_cell z=-count+mth_cell elseif sixth==3 x=-mth_cell y=0 z=-count+mth_cell elseif sixth==4 x=-count+mth_cell y=-mth_cell z=0 elseif sixth==5 x=0 y=-count+mth_cell z=mth_cell elseif sixth==6 x=mth_cell y=0 z=count-mth_cell end curr_cell_index=[x,y,z] append!(index_of_cells, curr_cell_index) mth_cell=+1 end count+=1 end index_G2_G1=[] element=[] for i in index_of_cells g3=i[1] g3=i[2] g3=i[3] element=[g2+g3,g1+g3] append!(index_G2_G1,element) end return(index_G2_G1) end index = hex_index(N)
And it returns the following error:
BoundsError Stacktrace: [1] getindex at .\number.jl:78 [inlined] [2] hex_index(::Int64) at .\In[18]:58 [3] top-level scope at In[18]:69 [4] include_string(::Function, ::Module, ::String, ::String) at .\loading.jl:1091
I am not sure why? I am new to Julia and do not really understand the scope issue in Julia. I come from using Python...
-
Kriging interpolation using GeoStats package in Julia
I am trying to build a model for kriging interpolation using
GeoStats
package in julia. I have tried an example of 2D interpolations but the results are not accurate, as mentioned below.Code for 2D interpolation:
using KrigingEstimators, DataFrames, Variography, Plots OK = OrdinaryKriging(GaussianVariogram()) # interpolator object f(x) = sin(x) # fit it to the data: x_train = range(0, 10.0, length = 9) |> collect y_train = f.(x_train) scatter(x_train, y_train, label="train points") x_train = reshape(x_train, 1, length(x_train)) krig = KrigingEstimators.fit(OK, x_train, y_train) # fit function result = [] variance =[] test = range(0, 10, length = 101) |> collect y_test = f.(test) test = reshape(test, 1, length(test)) for i in test μ, σ² = KrigingEstimators.predict(krig, [i]) push!(result, μ) push!(variance, σ²) end df_krig_vario = DataFrame(:predict=>result, :real=>y_test, :variance=>variance) println(first(df_krig_vario, 5)) mean_var = sum(variance)/length(variance) println("") println("mean variance is $mean_var") test = reshape(test, length(test), 1) plot!(test, y_test, label="actual") plot!(test, result, label="predict", legend=:bottomright, title="Gaussian Variogram")
With reference to the above figure it can be seen that the interpolation prediction is not accurate. May I know, how to improve this accuracy?
-
How to create space-holder when field is empty or null?
The "locus" field displays a series of values.
I would like the values to display in a specific order AND I would like the empty or null fields to create a space-holder so that each value repeats in the same space in the following sections.
In the attached pictures, the values are grouped by sample date (also the details section is formatted with multiple columns).
Thank you!
-
How to define React component with conditional props interface?
i need to define "Field" component that renders
textarea
orinput
depends on propmultiline
I trying to do this like that:
import React from 'react'; type Props<T extends boolean = boolean> = { multiline: T } & T extends true ? React.HTMLProps<HTMLTextAreaElement> : React.HTMLProps<HTMLInputElement> export const Field: React.FC<Props> = ({ multiline, ...props }) => { // error here const Element = multiline ? 'textarea' : 'input'; return <Element {...props} onInput={e => {}} />; // error here } // usage const result = ( <Field onChange={e => console.log(e.target.value)} /> // error here );
But typescript provide several errors like:
1 Property 'multiline' does not exist on type 'HTMLProps<HTMLInputElement> & { children?: ReactNode; }'.(2339) 2 [large error, more in playground] 3 Property 'value' does not exist on type 'EventTarget'.(2339)
How can i define such component?
-
Drupal hook to add label in multi-value field
I want to create Multi-value Drupal field programmatically.
I want to create a field with five input fields, of text-type
full-html
and I want to show labels to the left of the fields.Type of field : This will be full HTML
What is the correct hook to create fields programmatically, and add labels to the fields left. The fields input will be shown only in edit page
field
.I want to add labels to the label, how to proceed to add labels to the input field programmatically.