Using linked lists and structs - linked-list

I am trying to write an abstract data type to represent sets of integer items
using linked lists but I am already stuck. I'm not sure if it is possible to refer to one struct declaration from another. Here is my attempt:
struct linkedListElement{
int data;
struct linkedListElement * next;
};
struct linkedListSet {
struct linkedListElement * firstElement;
struct linkedListElement * header;
struct linkedListElement * current;
struct linkedListElement * temp;
header = firstElement;
};
Is it possible to do it this way or is there an easier way?

It is possible for one struct definition to refer to another struct defintion – you do it correctly in your code:
struct linkedListSet {
struct linkedListElement * firstElement;
If you mean "set" as in "an unordered collection of items without duplicates", then the important logic will be in how you manipulate your underlying data structure to enforce those constraints. For example with your singly-linked list, you must iterate the entire list before adding an item to check for duplicates.
header = firstElement;
This line is not allowed in a struct definition.

Related

Variable name in dot notation in Swift

I want to use variable names in dot notation in Swift.
I'm wrestling with trying to make sense of JSON in Swift, and having a really hard time doing things that are so easy in JS (like cycling through objects, etc).
I have variables of custom types:
var questionConfiguration: QuestionConfiguration
var priorityConfiguration: PriorityConfiguration
Each of these types has an attribute, displayOrder, I want to access this dynamically. I have tried various things, including the following (i is a variable of type Int):
var configs = [self.questionConfiguration, self.priorityConfiguration]
print([configs[i]].displayOrder)
var configs = ["questionConfiguration", "priorityConfiguration"]
print([configs[i]].displayOrder)
How can I achieve this?
EDIT:
struct QuestionConfiguration: Codable {
var displayOrder: Int
}
struct PriorityConfiguration: Codable {
var displayOrder: Int
}
You can create a protocol for same property name then you can access it easily
protocol SameProp {
var displayOrder: Int {get set}
}
class QuestionConfiguration : SameProp {
var displayOrder : Int = 4
}
class PriorityConfiguration : SameProp {
var displayOrder : Int = 6
}
var questionConfiguration: QuestionConfiguration = QuestionConfiguration()
var priorityConfiguration: PriorityConfiguration = PriorityConfiguration()
var configs = [questionConfiguration, priorityConfiguration] as [SameProp]
for elements in configs{
print(elements.displayOrder) // will print 4 and 6
}
Swift is very particular about data types and I suspect you are experiencing challenges because of it.
When you do this:
var configs = [self.questionConfiguration, self.priorityConfiguration]
In Swift, all the elements in an array have to have the same type. You've not given Swift any hints about what types this array should contain so the compiler has to infer a type. QuestionConfiguration and PriorityConfiguration are two different types. So the compiler is likely to infer that configs is of type [Any] also called Array<Any>.
Then you try something like this:
configs[i].displayOrder (not sure why your code has the extra brackets)
But configs[i] is inferred to be of type Any and that type doesn't have a displayOrder property so the compiler complains.
You need to tell the compiler that these types share some properties. One way to do that would be to add a protocol that describes what they share:
protocol DisplayOrderable {
var displayOrder: Int { get }
}
struct QuestionConfiguration: DisplayOrderable, Codable {
var displayOrder: Int
}
struct PriorityConfiguration: DisplayOrderable, Codable {
var displayOrder: Int
}
then you could use
var configs: [any DisplayOrderable] = [self.questionConfiguration, self.priorityConfiguration]
And configs[i].displayOrder should work.

Dynamic Struct Variable Name

I define a struct as follows:
struct MyModel : Decodable {
var id : Int
var amount: Int
let myNewTableId : Int
let userId : Int
let myNewTable : MyNewTable
}
I then use this struct to convert JSON data into an object using JSONDecoder().decode.
The problem is that the myNewTable part of myNewTableId and myNewTable are based on an alias given to the SQL table they originate from. So if the alias is abc the fields should be abcId and abc and if its def it should be defId and def. I've saved this alias into a variable:
let MY_NEW_TABLE_ALIAS = "myNewT"
Is there a way to construct the variable names in the struct dynamically using MY_NEW_TABLE_ALIAS. Ideally, when the alias changes on the SQL side, I just want to update one variable, instead of having to update every single struct which uses that table.
The simple way is to convert the json first to a string and replace occurrences with the needed key / use CodingKeys and make the struct as it is , btw you can't have dynamic variable names

Specify a generic of a generic type in Swift

let ContentData be a class that is intended to be subclassed and create a struct that will hold on to some generic properties...
struct Properties<T: ContentData, U: Paged<ContentData>> {
let contentDataSubclass: T
let pagedContentData: U
}
Instantiate like so:
let properties = Properties<FAQ, Paged<QuestionAnswer>>(contentData: faq!, contentDataProperty: faq!.questionAndAnswers)
Note: Both FAQ and QuestionAnswer are subclasses of ContentData
The compiler complains saying:
error: 'Properties' requires that 'Paged<QuestionAnswer>' inherit from 'Paged<ContentData>'
Do I need a where clause of my Properties struct to specify that my object of type U is also of generic type? How does this work?
The goal is to write a struct definition that will accept multiple levels of generics. Maybe something like:
struct Properties<T: ContentData, U: Paged<V: ContentData>>

Allocating memory in kernel space for struct

If I declare a struct A and use that in another struct B. Like struct B { struct A; int len ; } and then I allocate memory for struct B, do I still need to allocate memory for struct A separately ?
What if I use struct *A inside ?
If struct A is embedded into struct B:
struct B {struct A a; int len;}
then you need to allocate memory only for struct B.
If struct B has a pointer to struct A:
struct B {struct A* a; int len;}
then you should allocate both structs, and assign pointer to allocated struct A to field a.

D: What will s refer to in foreach(ref s; sections[0..$/2+1])

What are the indices these two foreach loops will iterate over:
struct Section{}
Section[] sections;
// assuming we have 10 sections
foreach(ref s; sections[0..$/2+1]) {
// do something
}
foreach_reverse(ref s; sections[$/2..$])
{
// do something
}
the first will iterate over 0-sections.length/2+1=6 (exclusive) and the second will iterate 10-5
the $ in the index refers to the length of the array
and the array[a..b] notation expands to array.opSlice(a,b) that returns a partial view of the array
In D, an empty struct has a size 1. The rationale is the same as in C++: see here for a relevant question and the rationale. So, your array will contain dummy 1-byte elements.
Let us check this behavior:
import std.stdio;
struct Section{}
Section[] sections = new Section [10];
void main () {
foreach(ref s; sections[0..$/2+1]) {
writeln (&s);
}
}
To me, this prints:
42208C
42208D
42208E
42208F
422090
422091
which are consecutive addresses in memory.

Resources