Search Results

Search found 374 results on 15 pages for 'traverse'.

Page 2/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • PHP - Find parent key of array

    - by Jordan Rynard
    I'm trying to find a way to return the value of an array's parent key. For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002". The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though. [0] => Array ( [data] => [id] => 0000 [name] => Swirl [categories] => Array ( [0] => Array ( [id] => 0001 [name] => Whirl [products] => Array ( [0] => Array ( [id] => 0002 [filename] => 1.jpg ) [1] => Array ( [id] => 0003 [filename] => 2.jpg ) ) ) ) )

    Read the article

  • C++ print out a binary search tree

    - by starcorn
    Hello, Got nothing better to do this Christmas holiday, so I decided to try out making a binary search tree. I'm stuck with the print function. How should the logic behind it work? Since the tree is already inserting it in a somewhat sorted order, and I want to print the tree from smallest values to the biggest. So I need to travel to the furthest left branch of the tree to print the first value. Right, so after that how do I remember the way back up, do I need to save the previous node? A search in wikipedia gave me an solution which they used stack. And other solutions I couldn't quite understand how they've made it, so I'm asking here instead hoping someone can enlight me. I also wonder my insert function is OK. I've seen other's solution being smaller. void treenode::insert(int i) { if(root == 0) { cout << "root" << endl; root = new node(i,root); } else { node* travel = root; node* prev; while(travel) { if(travel->value > i) { cout << "travel left" << endl; prev = travel; travel = travel->left; } else { cout << "travel right" << endl; prev = travel; travel = travel->right; } } //insert if(prev->value > i) { cout << "left" << endl; prev->left = new node(i); } else { cout << "right" << endl; prev->right = new node(i); } } } void treenode::print() { node* travel = root; while(travel) { cout << travel->value << endl; travel = travel->left; } }

    Read the article

  • Counting leaf nodes in hierarchical tree

    - by timn
    This code fills a tree with values based their depths. But when traversing the tree, I cannot manage to determine the actual number of children. node-cnt is always 0. I've already tried node-parent-cnt but that gives me lots of warnings in Valgrind. Anyway, is the tree type I've chosen even appropriate for my purpose? #include <string.h> #include <stdio.h> #include <stdlib.h> #ifndef NULL #define NULL ((void *) 0) #endif // ---- typedef struct _Tree_Node { // data ptr void *p; // number of nodes int cnt; struct _Tree_Node *nodes; // parent nodes struct _Tree_Node *parent; } Tree_Node; typedef struct { Tree_Node root; } Tree; void Tree_Init(Tree *this) { this->root.p = NULL; this->root.cnt = 0; this->root.nodes = NULL; this->root.parent = NULL; } Tree_Node* Tree_AddNode(Tree_Node *node) { if (node->cnt == 0) { node->nodes = malloc(sizeof(Tree_Node)); } else { node->nodes = realloc( node->nodes, (node->cnt + 1) * sizeof(Tree_Node) ); } Tree_Node *res = &node->nodes[node->cnt]; res->p = NULL; res->cnt = 0; res->nodes = NULL; res->parent = node; node->cnt++; return res; } // ---- void handleNode(Tree_Node *node, int depth) { int j = depth; printf("\n"); while (j--) { printf(" "); } printf("depth=%d ", depth); if (node->p == NULL) { goto out; } printf("value=%s cnt=%d", node->p, node->cnt); out: for (int i = 0; i < node->cnt; i++) { handleNode(&node->nodes[i], depth + 1); } } Tree tree; int curdepth; Tree_Node *curnode; void add(int depth, char *s) { printf("%s: depth (%d) > curdepth (%d): %d\n", s, depth, curdepth, depth > curdepth); if (depth > curdepth) { curnode = Tree_AddNode(curnode); Tree_Node *node = Tree_AddNode(curnode); node->p = malloc(strlen(s)); memcpy(node->p, s, strlen(s)); curdepth++; } else { while (curdepth - depth > 0) { if (curnode->parent == NULL) { printf("Illegal nesting\n"); return; } curnode = curnode->parent; curdepth--; } Tree_Node *node = Tree_AddNode(curnode); node->p = malloc(strlen(s)); memcpy(node->p, s, strlen(s)); } } void main(void) { Tree_Init(&tree); curnode = &tree.root; curdepth = 0; add(0, "1"); add(1, "1.1"); add(2, "1.1.1"); add(3, "1.1.1.1"); add(4, "1.1.1.1.1"); add(2, "1.1.2"); add(0, "2"); handleNode(&tree.root, 0); }

    Read the article

  • Python - Is there a better/efficient way to find a node in tree?

    - by Sej P
    I have a node data structure defined as below and was not sure the find_matching_node method is pythonic or efficient. I am not well versed with generators but think there might be better solution using them. Any ideas? class HierarchyNode(): def __init__(self, nodeId): self.nodeId = nodeId self.children = {} # opted for dictionary to help reduce lookup time def addOrGetChild(self, childNode): return self.children.setdefault(childNode.nodeId,childNode) def find_matching_node(self, node): ''' look for the node in the immediate children of the current node. if not found recursively look for it in the children nodes until gone through all nodes ''' matching_node = self.children.get(node.nodeId) if matching_node: return matching_node else: for child in self.children.itervalues(): matching_node = child.find_matching_node(node) if matching_node: return matching_node return None

    Read the article

  • Logic that can traverse all possible layouts, but not checking every combination of identical pieces?

    - by George Bailey
    Suppose we have a grid of arbitrary size, which is filled by blocks of various widths and heights. There are many 2x2 blocks (meaning they take a total of 4 cells in the grid) and many 3x3 blocks, as well as some 5x4, 4x5, 2x3, etc. I was hoping I could set up a program that would look at all possible layouts, and rank them, and find the best one. Simply it would look at all possible positions of these blocks, and see what setup is the best rank. (the rank based on how many of these can be connected by a roadway system of 1x1 road blocks, and how many squares can be left empty after this is done. - wanting to fit the most blocks as possible with the least roads.) My question, is how should I traverse all the possibilities? I could take all the blocks and try them one at a time, but since all 2x2 blocks are equal, and there are a couple dozen of them, there is no point in trying every combination there, as in the following AA BBB AA BBB CCBBB CCEEE DD EEE DD EEE is exactly the same as CC EEE CC EEE AAEEE AABBB DD BBB DD BBB You notice that there are 2 3x3 blocks and 3 2x2 blocks in my two examples. Based on the model I have now, the computer would try both of these combinations, as well as many others. The problem is that it is going to try every single possible variation of my couple dozen 2x2 blocks. And that is sorely inefficient. Is there a reasonable way to take out this duplicated work, somehow getting the computer program to treat all 2x2 blocks as equal/identical, instead of one requiring rearranging/swapping of these identical blocks? Can this be done?

    Read the article

  • How can I traverse the EMF object tree generated by Xtext?

    - by reprogrammer
    I'm using Xtext to define my DSL. Xtext generates a parser that lets me traverse the EMF model of my input DSL. I'd like to translate this EMF model into some other tree. To do this translation, I need to traverse the tree. But, I couldn't find a visitor class for the EMF model generated by Xtext. The closest thing that I've found is a Switch class that visits a single node. I can traverse the EMF model myself and invoke the Switch class on each node that I visit. But, I wonder if there exists a visitor functionality in Xtext that implements the model traversal.

    Read the article

  • Traverse tree with results. Maybe type in Java?

    - by Angelo.Hannes
    I need to check a tree's node state. It can either be OK or NOT_OK. But that state is dependent on its children. So for a node to be OK, every of its children needs to be OK. If one or more of its children is NOT_OK the whole node is NOT_OK. To determine the state of a node I need to aggregate some properties of the node. So I thought of two possible implementations. And they are more or less covered in this question: Why is Option/Maybe considered a good idea and checked exceptions are not? Exception I could pass the properties up the recursion path, and throw an exception if something went wrong. Maybe I implement an Maybe type and let it either hold an error or the aggregated properties. Maybe it is more an Either. I tend towards the last option. And I'm thinking of an enum with two objects. Where I can additionally set those aggregated properties. Am I on the right track? I'm not familiar with the new JDK8 functional stuff. But I'm stuck on JDK7 anyway, so please focus on JDK7.

    Read the article

  • How can I traverse a reverse generic relation in a Django template?

    - by user569139
    I have the following class that I am using to bookmark items: class BookmarkedItem(models.Model): is_bookmarked = models.BooleanField(default=False) user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() And I am defining a reverse generic relationship as follows: class Link(models.Model): url = models.URLField() bookmarks = generic.GenericRelation(BookmarkedItem) In one of my views I generate a queryset of all links and add this to a context: links = Link.objects.all() context = { 'links': links } return render_to_response('links.html', context) The problem I am having is how to traverse the generic relationship in my template. For each link I want to be able to check the is_bookmarked attribute and change the add/remove bookmark button according to whether the user already has it bookmarked or not. Is this possible to do in the template? Or do I have to do some additional filtering in the view and pass another queryset?

    Read the article

  • Reasonably faster way to traverse a directory tree in Python?

    - by Sridhar Ratnakumar
    Assuming that the given directory tree is of reasonable size: say an open source project like Twisted or Python, what is the fastest way to traverse and iterate over the absolute path of all files/directories inside that directory? I want to do this from within Python (subprocess is allowed). os.path.walk is slow. So I tried ls -lR and tree -fi. For a project with about 8337 files (including tmp, pyc, test, .svn files): $ time tree -fi > /dev/null real 0m0.170s user 0m0.044s sys 0m0.123s $ time ls -lR > /dev/null real 0m0.292s user 0m0.138s sys 0m0.152s $ time find . > /dev/null real 0m0.074s user 0m0.017s sys 0m0.056s $ tree appears to be faster than ls -lR (though ls -R is faster than tree, but it does not give full paths). find is the fastest. Can anyone think of a faster and/or better approach? On Windows, I may simply ship a 32-bit binary tree.exe or ls.exe if necessary. Update 1: Added find

    Read the article

  • Doctrine: How to traverse from an entity to another 'linked' entity?

    - by ropstah
    I'm loading 3 different tables using a cross-join in Doctrine_RawSql. This brings me back the following object: User -> User class (doctrine base class) Settings -> DoctrineCollection of Setting User_Settings -> DoctrineCollection of User_Setting The object above is the result of a many-to-many relationship between User and Setting where User_Setting acts as a reference table. User_Setting also contains another field named value. This obviously contains the value of the corresponding Setting. All good so far, however the Settings and User_Settings properties of the returned User object are in no way linked to each other (apart from the setting_id field ofcourse). Is there any direct way to traverse directly from the Settings property to the corresponding User_Settings property? This is the corresponding query: $sets = new Doctrine_RawSql(); $sets->select('{us.*}, {s.*}, {uset.*}') ->from('(User us CROSS JOIN Setting s) LEFT JOIN User_Setting uset ON us.user_id = uset.user_id AND s.setting_id = uset.setting_id') ->addComponent('us', 'User us') ->addComponent('uset', 'us.User_Setting uset') ->addComponent('s', 'us.Setting s') ->where('s.category_id = ? AND us.usr_auto_key = ?',array(1, 1)); $sets = $sets->execute();

    Read the article

  • How do I execute find with GNU xargs to traverse a set of directories?

    - by wilhelmtell
    $ echo {a,b,c}.h d e.h |xargs -IA find A -name '*.h' find: `a.h b.h c.h d e.h': No such file or directory $ echo -e a.h\\nb.h c.h d e.h |xargs -IA find A -name '*.h' a.h find: `b.h c.h d e.h': No such file or directory The problem is that -I implies xargs will assume arguments are delimited by newline. I'm not sure why that is. I reckon I can solve this problem with sed, but I wonder if there's an xargs trick or idiom I'm not familiar with that people use to solve this. I'm looking for a solution that will also work on OS X. On OS X the xargs -J switch seems to work fine. The manpage claims this switch will just control where the arguments are placed for the executable -- which is exactly what I want.

    Read the article

  • How do I traverse the filesystem looking for a regex match?

    - by editor
    I know this is teeball for veteran sysadmins, but I'm looking to search a directory tree for file contents that match a regex (here, the word "Keyword"). I've gotten that far, but now I'm having trouble ignoring files in a hidden (.svn) file tree. Here's what I'm working with: find . -exec grep "Keyword" '{}' \; -print Reading sites via search I know that I need to negate the name flag, but I can't it working in the right order.

    Read the article

  • How do you traverse and store XML in Blackberry Java app?

    - by Greg
    I'm having a problem accessing the contents of an XML document. My goal is this: Take an XML source and parse it into a fair equivalent of an associative array, then store it as a persistable object. the xml is pretty simple: <root> <element> <category_id>1</category_id> <name>Cars</name> </element> <element> <category_id>2</category_id> <name>Boats</name> </element> </root> Basic java class below. I'm pretty much just calling save(xml) after http response above. Yes, the xml is properly formatted. import java.io.IOException; import java.util.Hashtable; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.Vector; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore; import net.rim.device.api.xml.parsers.DocumentBuilder; import net.rim.device.api.xml.parsers.DocumentBuilderFactory; public class database{ private static PersistentObject storeVenue; static final long key = 0x2ba5f8081f7ef332L; public Hashtable hashtable; public Vector venue_list; String _node,_element; public database() { storeVenue = PersistentStore.getPersistentObject(key); } public void save(Document xml) { venue_list = new Vector(); storeVenue.setContents(venue_list); Hashtable categories = new Hashtable(); try{ DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.isValidating(); xml.getDocumentElement ().normalize (); NodeList list=xml.getElementsByTagName("*"); _node=new String(); _element = new String(); for (int i=0;i<list.getLength();i++){ Node value=list.item(i).getChildNodes().item(0); _node=list.item(i).getNodeName(); _element=value.getNodeValue(); categories.put(_element, _node); } } catch (Exception e){ System.out.println(e.toString()); } venue_list.addElement(categories); storeVenue.commit(); } The code above is the work in progress, and is most likely heavily flawed. However, I have been at this for days now. I can never seem to get all child nodes, or the name / value pair. When I print out the vector as a string, I usually end up with results like this: [{ = root, = element}] and that's it. No "category_id", no "name" Ideally, I would end up with something like [{1 = cars, 2 = boats}] Any help is appreciated. Thanks

    Read the article

  • How to traverse the item in the collection in a List or Observable collection?

    - by Ashish Ashu
    I have a collection that is binded to my Listview. I have provided options to user to "move up" "move down" the selected item in the list view. I have binded the selected item of the listview to my viewmodel, hence I get the item in the collection on which user want to do the operation. I have attached "move up" "move down" commands in my viewmodel. I want what is the best way to move up and down in the collection in the collection which is reflected in the list view. Please suggest.

    Read the article

  • How to traverse table in Jquery and add a class?

    - by SWL
    I have a simple table of two rows. The first column is required, but the others are not; however, I would like them to be required in pairs. So if the user enters a value for Quantity3, then Size3 should also now be required. As a fiddle: http://jsfiddle.net/NaRts/7/ <tr> <td><input name="qty1[492]" class="qty required" type="text"></td> <td><input name="qty2[492]" class="qty" type="text"></td> <td><input name="qty3[492]" class="qty" type="text"></td> </tr><tr> <td><input name="size1[492]" type="text" class="size required" ></td> <td><input name="size2[492]" type="text" class="size" ></td> <td><input name="size3[492]" type="text" class="size" ></td> </tr> And the simple jQuery I have is: $('.qty').keyup(function() { var s = $(this).attr('name'); // = qty3[418] var qtyID = s.replace(/[^1-9\[\]]/g, ""); // = 3[418] var SizeID = "size" + qtyID; var $sizeInput = $(this).closest('tr').next().find(SizeID); $sizeInput.css('background-color', 'green'); $sizeInput.addClass('required'); //I tried this too but it didn't work //$(this).parent().find(SizeID).addClass('required'); });? ? Any help is much appreciated.

    Read the article

  • Does the java JFC hash table use seperate chaining resolution? Can I traverse each list in the table

    - by Matt
    I have written a program to store a bunch of strings in a JFC hash table. There are defiantly collisions going on, but I don't really know how it is handling them. My ultimate goal is to print the number of occurrences of each string in the table, and traversing the bucket or list would work nicely. Or maybe counting the collisions? Or do you have another idea of how I could get a count of the elements?

    Read the article

  • how to use anonymous generic delegate in C# 2.0

    - by matti
    Hi. I have a class called NTree: class NTree<T> { public NTree(T data) { this.data = data; children = new List<NTree<T>>(); _stopTraverse = false; } ... public void Traverse(NTree<T> node, TreeVisitor<T> visitor) { try { _stopTraverse = false; Traverse(node, visitor); } finally { _stopTraverse = false; } } private void TraverseInternal(NTree<T> node, TreeVisitor<T> visitor) { if (_stopTraverse) return; if (!visitor(node.data)) { _stopTraverse = true; } foreach (NTree<T> kid in node.children) Traverse(kid, visitor); } When I try to use Traverse with anonymous delegate I get: Argument '2': cannot convert from 'anonymous method' to 'NisConverter.TreeVisitor' The code: tTable srcTable = new tTable(); DataRow[] rows; rootTree.Traverse(rootTree, delegate(TableRows tr) { if (tr.TableName == srcTable.mappingname) { rows = tr.Rows; return false; } }); This however produces no errors: static bool TableFinder<TableRows>(TableRows tr) { return true; } ... rootTree.Traverse(rootTree, TableFinder); I have tried to put "arrowhead-parenthisis" and everything to anonymous delegate but it just does not work. Please help me! Thanks & BR -Matti

    Read the article

  • Sorting a Linked List [closed]

    - by Mohit Sehgal
    I want to sort a linked list. Here Node is class representing a node in a Linked List I have written a code to bubble sort a linked list. Program does not finishes execution. Kindly point out the mistakes. class Node { public: int data; public: Node *next; Node() { data=0;next=0; } Node(int d) { data=d; } void setData(int d) { data=d; } void print() { cout<<data<<endl; } bool operator==(Node n) { return this->data==n.data; } bool operator >(Node d) { if((this->data) > (d.data)) return true; return false; } }; class LList { public: int noOfNodes; Node *start;/*Header Node*/ LList() { start=new Node; noOfNodes=0;start=0; } void addAtFront(Node* n) { n->next=(start); start=n; noOfNodes++; } void addAtLast(Node* n) { Node *cur=(start); n->next=NULL; if(start==NULL) { start=n; noOfNodes++; return; } while(cur->next!=NULL) { cur=cur->next; } cur->next=n; noOfNodes++; } void addAtPos(Node *n,int pos) { if(pos==1) { addAtFront(n);return; } Node *cur=(start); Node *prev=NULL; int curPos=0; n->next=NULL; while(cur!=NULL) { curPos++; if(pos==curPos+1) { prev=cur; } if(pos==curPos) { n->next=cur; prev->next=n; break; } cur=cur->next; } noOfNodes++; } void removeFirst() { Node *del=start; start=start->next; delete del; noOfNodes--; return; } void removeLast() { Node *cur=start,*prev=NULL; while(cur->next!=NULL) { prev=cur; cur=cur->next; } prev->next=NULL; Node *del=cur->next; delete del; noOfNodes--; return; } void removeNodeAt(int pos) { if(pos<1) return; if(pos==1) { removeFirst();return;} int curPos=1; Node* cur=start->next; Node* prev=start; Node* del=NULL; while(curPos<pos&&cur!=NULL) { curPos++; if(curPos==pos) { del=cur; prev->next=cur->next; cur->next=NULL; delete del; noOfNodes--; break; } prev=prev->next; cur=cur->next; } } void removeNode(Node *d) { Node *cur=start; if(*d==*cur) { removeFirst();return; } cur=start->next; Node *prev=start,*del=NULL; while(cur!=NULL) { if(*cur==*d) { del=cur; prev->next=cur->next; delete del; noOfNodes--; break; } prev=prev->next; cur=cur->next; } } int getPosition(Node data) { int pos=0; Node *cur=(start); while(cur!=NULL) { pos++; if(*cur==data) { return pos; } cur=cur->next; } return -1;//not found } Node getNode(int pos) { if(pos<1) return -1;// not a valid position else if(pos>noOfNodes) return -1; // not a valid position Node *cur=(start); int curPos=0; while(cur!=NULL) { if(++curPos==pos) return *cur; cur=cur->next; } } void reverseList()//reverse the list { Node* cur=start->next; Node* d=NULL; Node* prev=start; while(cur!=NULL) { d=cur->next; cur->next=start; start=cur; prev->next=d; cur=d; } } void sortBubble() { Node *i=start,*j=start,*prev=NULL,*temp=NULL,*after=NULL; int count=noOfNodes-1;int icount=0; while(i->next!=NULL) { j=start; after=j->next; icount=0; while(++icount!=count) { if((*j)>(*after)) { temp=after->next; after->next=j; prev->next=j->next; j->next=temp; prev=after; after=j->next; } else{ prev=j; j=after; after=after->next; } } i=i->next; count--; } } void traverse() { Node *cur=(start); int c=0; while(cur!=NULL) { // cout<<"start"<<start; c++; cur->print(); cur=cur->next; } noOfNodes=c; } ~LList() { delete start; } }; int main() { int n; cin>>n; int d; LList list; Node *node; Node *temp=new Node(2123); for(int i=0;i<n;i++) { cin>>d; node=new Node(d); list.addAtLast(node); } list.addAtPos(temp,1); cout<<"traverse\n"; list.traverse(); temp=new Node(12); list.removeNode(temp); cout<<"12 removed"; list.traverse(); list.reverseList(); cout<<"\nreversed\n"; list.traverse(); cout<<"bubble sort\n"; list.sortBubble(); list.traverse(); getch(); delete node; return 0; }

    Read the article

  • Is it just me or is this a baffling tech interview question

    - by Matthew Patrick Cashatt
    Background I was just asked in a tech interview to write an algorithm to traverse an "object" (notice the quotes) where A is equal to B and B is equal to C and A is equal to C. That's it. That is all the information I was given. I asked the interviewer what the goal was but apparently there wasn't one, just "traverse" the "object". I don't know about anyone else, but this seems like a silly question to me. I asked again, "am I searching for a value?". Nope. Just "traverse" it. Why would I ever want to endlessly loop through this "object"?? To melt my processor maybe?? The answer according to the interviewer was that I should have written a recursive function. OK, so why not simply ask me to write a recursive function? And who would write a recursive function that never ends? My question: Is this a valid question to the rest of you and, if so, can you provide a hint as to what I might be missing? Perhaps I am thinking too hard about solving real world problems. I have been successfully coding for a long time but this tech interview process makes me feel like I don't know anything. Final Answer: CLOWN TRAVERSAL!!! (See @Matt's answer below) Thanks! Matt

    Read the article

  • How do I handle the Maybe result of at in Control.Lens.Indexed without a Monoid instance

    - by Matthias Hörmann
    I recently discovered the lens package on Hackage and have been trying to make use of it now in a small test project that might turn into a MUD/MUSH server one very distant day if I keep working on it. Here is a minimized version of my code illustrating the problem I am facing right now with the at lenses used to access Key/Value containers (Data.Map.Strict in my case) {-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving, TemplateHaskell #-} module World where import Control.Applicative ((<$>),(<*>), pure) import Control.Lens import Data.Map.Strict (Map) import qualified Data.Map.Strict as DM import Data.Maybe import Data.UUID import Data.Text (Text) import qualified Data.Text as T import System.Random (Random, randomIO) newtype RoomId = RoomId UUID deriving (Eq, Ord, Show, Read, Random) newtype PlayerId = PlayerId UUID deriving (Eq, Ord, Show, Read, Random) data Room = Room { _roomId :: RoomId , _roomName :: Text , _roomDescription :: Text , _roomPlayers :: [PlayerId] } deriving (Eq, Ord, Show, Read) makeLenses ''Room data Player = Player { _playerId :: PlayerId , _playerDisplayName :: Text , _playerLocation :: RoomId } deriving (Eq, Ord, Show, Read) makeLenses ''Player data World = World { _worldRooms :: Map RoomId Room , _worldPlayers :: Map PlayerId Player } deriving (Eq, Ord, Show, Read) makeLenses ''World mkWorld :: IO World mkWorld = do r1 <- Room <$> randomIO <*> (pure "The Singularity") <*> (pure "You are standing in the only place in the whole world") <*> (pure []) p1 <- Player <$> randomIO <*> (pure "testplayer1") <*> (pure $ r1^.roomId) let rooms = at (r1^.roomId) ?~ (set roomPlayers [p1^.playerId] r1) $ DM.empty players = at (p1^.playerId) ?~ p1 $ DM.empty in do return $ World rooms players viewPlayerLocation :: World -> PlayerId -> RoomId viewPlayerLocation world playerId= view (worldPlayers.at playerId.traverse.playerLocation) world Since rooms, players and similar objects are referenced all over the code I store them in my World state type as maps of Ids (newtyped UUIDs) to their data objects. To retrieve those with lenses I need to handle the Maybe returned by the at lens (in case the key is not in the map this is Nothing) somehow. In my last line I tried to do this via traverse which does typecheck as long as the final result is an instance of Monoid but this is not generally the case. Right here it is not because playerLocation returns a RoomId which has no Monoid instance. No instance for (Data.Monoid.Monoid RoomId) arising from a use of `traverse' Possible fix: add an instance declaration for (Data.Monoid.Monoid RoomId) In the first argument of `(.)', namely `traverse' In the second argument of `(.)', namely `traverse . playerLocation' In the second argument of `(.)', namely `at playerId . traverse . playerLocation' Since the Monoid is required by traverse only because traverse generalizes to containers of sizes greater than one I was now wondering if there is a better way to handle this that does not require semantically nonsensical Monoid instances on all types possibly contained in one my objects I want to store in the map. Or maybe I misunderstood the issue here completely and I need to use a completely different bit of the rather large lens package?

    Read the article

  • Name "main::a" used only once: possible typo at ... line ...

    - by knorv
    When running the following Perl code ... use Data::Traverse qw(traverse); use warnings; my $struct = [ 1, 2, { foo => 42 }, [ 3, 4, [ 5, 6, { bar => 43 } ] ], 7, 8 ]; traverse { print "$a => $b\n" if /HASH/ } $struct; ... the warning Name "main::[ab]" used only once: possible typo is given. Since the use of $a and $b is clearly not a typo in this case I want to get rid of the warning. How do I do that while still using warnings?

    Read the article

  • Scene Graph Traversing Techniques

    - by Bunkai.Satori
    Scene Graph seems to be the most effective way of representing the game world. The game world usually tends to be as large as the memory and device can handle. In contrast, the screen of the device captures only a fraction of the Game World/Scene Graph. Ideally, I wish to process(update and render) only the visible game objects/nodes on per-frame basis. My question therefore is, how to traverse the scene graph so, that I will focus only on the game notes that are in the camera frustum? How to organize data so that I can easily focus only on the scene graph nodes visible to me? What are techniques to minimize scenegraph traversal time? Is there such way as more effective traversal, or do I have to traverse whole scene graph on per-frame basis?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >