Adding improper tail to given Erlang list - list

How do I add an improper tail (e.g. |<<>>) to a proper Erlang list "Parent" with an arbitrary number of elements? I need this to create a range scan upper limit value for matchspecs on a MNESIA table where list keys represent object hierarchy.
To my understanding (inspired by the sext project) any children of a parent key Parent=[T1,T2,T3] (T1,T2,T2 are arbitrary Erlang Terms) can be found with matchspecs asking for:
Child > [T1,T2,T3] and Child < [T1,T2,T3|<<>>]
Given only Parent as a whole, how do I calculate the upper value?

To get the improper list you're looking for, just append the empty binary <<>> to the list:
Parent ++ <<>>.
For example, if Parent is [t1,t2,t3]:
1> Parent = [t1,t2,t3].
[t1,t2,t3]
2> Parent ++ <<>>.
[t1,t2,t3|<<>>]

Related

Adding an element to a list and then reverse it

I'm learning Haskell, and attempting to understand lists.
From researching, to add an element to a list, you would normally do:
let numbers = [4,8,15,16,23,42]
numbers ++ [56]
but to quote this answer:
If you need to do this, there is usually a better way to structure
your algorithm. For example, you can build your list in reverse order
(adding elements at the beginning) and only call reverse at the end.
Code:
let numbers = [23,43,56]
let newNumbers = 69:numbers
reverse newNumbers
Output:
[56,43,23,69]
Question:
Is the code I've written correct according to the quoted answer?
I want to understand the terminology a little better, can I say I'm adding elements to the head of the list? From my understanding, every new element would be the first element, and the value returned when I write head newNumbers.
You need to distinguish between the linked list data structure and whatever list-like data type you are implementing with the linked list. You can do exactly two things to modify a linked list: prepend a new head to the list, and remove the current head (if the linked list isn't empty).
The use case the quote talks about is common for a queue data type: you can add to one end and remove from the other end. You can implement this using two linked lists, by adding new elements to one list and removing elements from the other. The implementation of the queue takes care of reversing as necessary to ensure that you never remove an item before every other item inserted previously is removed.
data Queue a = Queue [a] [a]
-- Put new elements on the incoming list.
addToQueue :: a -> Queue a -> Queue a
addToQueue x (Queue incoming outgoing) = Queue (x:incoming) outgoing
-- Take elements from the outgoing list, whose elements are stored
-- in the reverse order that they were added to the incoming list
-- previously.
removeFromQueue :: Queue a -> (a, Queue a)
removeFromQueue (Queue [] []) = error "Cannot remove from empty queue"
removeFromQueue (Queue incoming (x:xs)) = (x, Queue incoming xs)
removeFromQueue (Queue incoming []) = removeFromQueue (Queue [] (reverse incoming))
(We're not concerned with good ways to deal with removing from an empty queue here; just call it an error and leave it at that.)
Adding to the incoming list and removing from the outgoing list is easy. The tricky part is how and when we transfer items from the incoming list to the outgoing list. We only do so when the outgoing list is empty, and when it is, we transfer the entire incoming list at once, reversing it in the process. In other words, we're building up the incoming list in reverse,
but only ever reverse it when necessary, not after each and every single item is added.
Amortized analysis can be used to show that although reverse could be slow, it is balanced by the number of fast operations that precede and can follow it.

Elixir: Find middle item in list

I'm trying to learn Elixir. In most other languages i've battled with, this would be an easy task.
However, i can't seem to figure out how to access a list item by index in Elixir, which i need for finding the median item in my list. Any clarification would be greatly appreciated!
You will want to look into Enum.at/3.
a = [1,2,3,4,5]
middle_index = a |> length() |> div(2)
Enum.at(a, middle_index)
Note: This is expensive as it needs to traverse the entire list to find the length of the list, and then traverse halfway through the list to find what the actual element is. Generally speaking, if you need random access to an item in a list, you should be looking for a different data structure.
This is how I would do it:
Enum.at(x, div(length(x), 2))
Enum.at/3 retrieves the value at a particular index of an enumerable. div/2 is the equivalent of the Python 2.x / integer division.

How to retrieve map nodes with keys not scalars?

I want to use insensively yaml-cpp in a C++ project, as it fits my needs perfectly. But I want to update one node from another node, i.e. properly add non-existant nodes from one mode to another, or replace existing values of existing ones. I can't find how to do this simply with the current interface...
So I try to do this with a simple loop on an iterator. I figure out that the following thing does not work while traversing a map node:
if (node_1[it->first]) /*...*/
It does not find any node! So, for map nodes with scalars as keys, the test if (node_1[it->first.Scalar()]) /*...*/ works well. My problem is to do the same with sequence keys. How can I do that?
EDIT
Here is an example of YAML document:
---
#Fake entry
Time: 0.1.1.2
ID: 25814
Emitter: Me
Line : {
orig: 314,
st: 512
}
Message : |
This is a fake error
#More difficult
[0,1,2,3] : my_address
[5, 6, 7, 8] : an_address
...
This document is loaded without any problem into a Node, say doc1; I want now modify some entries with respect to another YAML document, such as:
---
Comment: what a dummy file!
Emitter: You
[0,1,2,3] : address changed
...
So I load this second document into a Node doc2, and I want to update doc1 with the nodes of doc 2. The first key of doc 2 is not present in doc 1 and is a scalar, so I can do doc1[it->first.Scalar()] = it->second. The second key is present, so the same instruction will update doc1, replacing the value linked with key Emitter. My problem is that I cannot succeed in finding the 3rd key inside doc1, as it is a sequence.
yaml-cpp doesn't offer generic equality testing for nodes, which is why your initial solution (which would have the best bet of working) didn't work.
Instead, yaml-cpp relies on typed equality testing. E.g., node[5] will convert all keys to integers to check key equality; it won't convert 5 to a node and then check equality that way. This is why your other solution will usually work - most of your keys are simple scalars, so they can match using std::string equality.
It appears you really want to "merge" two nodes; this has been on the yaml-cpp issues list for a while: https://code.google.com/p/yaml-cpp/issues/detail?id=41, and there's some discussion there which explains why it's a hard problem.
As a possible workaround, if you know the type of each node, you can explicitly cast before doing your comparison, e.g.:
doc1[it->first.as<T>()] = it->second;

Binary tree Breadth-first search

I'm using OCaml. I have type:
type 'a bt = Empty | Node of 'a * 'a bt * 'a bt;;
Also I have example BST:
let tree = Node(1,Node(2,Node(4,Empty,Empty),Empty),Node(3,Node(5,Empty,Node(6,Empty,Empty)),Empty));
I need to write function: breadthBT : 'a bt -> 'a list which will be Breadth-first search traversal. For above example tree it should returns [1; 2; 3; 4; 5; 6]
How to write that function? I can write only following function which uses DST :
let rec breadthBT tree =
if tree=Empty then []
else let Node(w,l,r)=tree in (w::breadthBT l)#breadthBT r;;
Above function returns (for example tree) [1; 2; 4; 3; 5; 6]. But I can't write function which uses BFS. Could you help me?
It is not a compilable solution. Just a tip.
You should iterate from top level root node to deep level nodes. Let our function receives accumulator for the answer and list of nodes (your 'a bt values) as second parameter. You can map this list by getting first element of triple and than you receive next part of answer. Also you need to evaluate next level of tree. For every node there are at most two descendants. You can map your list and apply _a_function_to receive list of descendants. It will be next level of your tree. And than --- recursion.
A will not specify this _a_function_. Try to study what is concatMap in google.
Happy hacking!
Imagine you stick your nose to the tree. Is it possible to traverse the tree in the breadth-first manner without bookmarking positions in your notepad? No, because the order can make you jump from one branch to another unrelated branch. So you need a notepad with "remaining positions to visit". You pick the next remaining position from the notepad and jump to it blindly. Since you erase visited positions from the notepad, you are at a node you have not visited yet. And since you cannot get up the tree without visiting intermediate nodes, you haven't visited the two nodes now above you. But you resist the instinct to climb the branches directly -- heck, this is breadth first order. You do not want to forget about these two unvisited nodes, so you want to put them into the notebook. Where do you put them, in front of the notebook or on its back? On the back of course, otherwise you would pick one of them immediately and that's what we want to avoid. Et voila: your notepad is a FIFO queue of nodes, which you keep (i.e. pass) around as an accumulator, but also consume to pick a subtree to visit.

Searching data stored in a tree

I have this data that is hierarchical and so I store it in a tree. I want to provide a search function to it. Do I have to create a binary tree for that? I don't want to have thousands of nodes twice. Isn't there a kind of tree that allows me to both store the data in the order given and also provide me the binary tree like efficient searching setup, with little overhead?
Any other data structure suggestion will also be appreciated.
Thanks.
EDIT:
Some details: The tree is a very simple "hand made" tree that can be considered very very basic. The thing is, there are thousands of names and other text that will be entered as data that I want to search but I don't want to traverse the nodes in a traditional way and need a fast search like binary search.
Also, importantly, the user must be able to see the structure he has entered and NOT the sorted one. So I cant keep it sorted to support the search. That is why I said I don't want to have thousands of nodes twice.
If you don't want to change your trees hierarchy use a map to store pointers to vertexes: std::map<SearchKeyType,Vertex*> M.
Every time when you will add vertex to your tree you need to add it to your map too. It's very easy: M[key]=&vertex. To find an element use M.find(key);, or M[key]; if you are sure that key exists.
If your tree has duplicate keys, then you should use a multimap.
Edit: If your key's size is too big, than you can use pointer to key instead of key:
inline bool comparisonFunction(SearchKeyType * arg1,SearchKeyType * arg2);
std::map<SearchKeyType *, Vertex *, comparisonFunction> M;
inline bool comparisonFunction(SearchKeyType * arg1,SearchKeyType * arg2)
{
return (*arg1)<(*arg2);
}
to search Element with value V you must write following:
Vertex * v = M[&V]; // assuming that element V exists in M