Class NTreeNode<K extends java.lang.Comparable<K>,V>
- java.lang.Object
-
- veve.datastructures.trees.NTreeNode<K,V>
-
- Type Parameters:
K
- The type of the nodes id. Must implementComparable
.V
- The type of thevalue
property of the node.
- All Implemented Interfaces:
java.lang.Comparable<NTreeNode<K,V>>
,java.lang.Iterable<NTreeNode<K,V>>
public class NTreeNode<K extends java.lang.Comparable<K>,V> extends java.lang.Object implements java.lang.Iterable<NTreeNode<K,V>>, java.lang.Comparable<NTreeNode<K,V>>
A tree node that has an id, a value and zero or more child nodes. Children of a node cannot have the same id. The id in aNTreeNode
cannot benull
but the value can benull
. The node is also required to have a reference to aNTree
which is the owner of the node but the node is not necessarily part of the tree who is its owner.A node can also be considered as the root of a subtree or node hierarchy even if it does not not formally form part of an
NTree
.All methods from
NTreeNode
that modify the node or subtree will update the indexes of theNTree
that owns this node if the node is formally part of the trhat tree so the indexes are automatically kept in sync with the node changes.The methods of this class that use functional interface arguments convert the lambda function passed to another lambda function that prevents NullPointerException from breaking the execution and instead make the lambda function return null or false or not execute if it is a Consumer. If a NullPointerException is thrown for a Predicate or BiPredicate argument the result of executing the lambda function would be false. If the parameter is of type Function then the result of the lambda function would be null.
Note that no method accepts null values as arguments except
setValue(Object)
, the variants oftreeGraph(java.lang.Integer, java.lang.Integer, java.util.function.Function<veve.datastructures.trees.NTreeNode<K, V>, R>)
andfindFirstWithValue(Object)
.The
NearestCommonAncestorTool
class can be used to find the nearest common ancestor between two nodes in a tree plus having other methods to get all nodes between the path between them and the their common ancestor.This class is not thread safe.
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description NTreeNode<K,V>
addNewChildren(NTreeNode<K,V>... children)
Adds new child nodes to this node.NTreeNode<K,V>
c(NTreeNode<K,V>... children)
Same asaddNewChildren(NTreeNode...)
.java.util.List<K>
childrenIds()
Returns aList
of the ids of this node's children.java.util.Map<K,V>
childrenIdsValuesMap()
Returns aMap
of where the keys are the ids of this node's children and the values are their values.java.util.List<NTreeNode<K,V>>
childrenList()
Returns aList
of this node's children.java.util.List<NTreeNode<K,V>>
childrenList(java.util.Collection<K> ids)
Returns aList
of this node's children whose ids are included in the passedCollection
of ids.java.util.List<NTreeNode<K,V>>
childrenList(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns aList
of this node's children for which the providedPredicate
evaluates totrue
.java.util.List<NTreeNode<K,V>>
childrenList(K... ids)
Similar tochildrenList(Collection)
but has a varargs parameter instead of aCollection
of nodesjava.util.Map<K,NTreeNode<K,V>>
childrenMap()
Returns aMap
of this node's children.java.util.Map<K,NTreeNode<K,V>>
childrenMap(java.util.Collection<K> ids)
Returns aMap
of this node's children that have ids that are in the providedCollection
of ids.java.util.Map<K,NTreeNode<K,V>>
childrenMap(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns aMap
of this node's children for which the providedPredicates
evaluates totrue
.java.util.Map<K,NTreeNode<K,V>>
childrenMap(K... ids)
Similar tochildrenMap(Collection)
but instead of having aCollection
as parameter it uses a varargs parameter.int
childrenSize()
Returns the number of children this node has.java.util.List<V>
childrenValues()
Returns aList
of the values of this node's children.NTreeNode<K,V>
childWithId(K id)
Returns the child node that matches the passed id.NTreeNode<K,V>
clone()
Returns a clone of this node and its descendant.NTreeNode<K,V>
clone(NTree<K,V> treeOfBelonging)
Returns a clone of this node and its descendant.NTreeNode<K,V>
cloneSingleNode()
Returns a clone of this node and sets its treeOfBelonging to the one this node has.NTreeNode<K,V>
cloneSingleNode(NTree<K,V> treeOfBelonging)
Returns a clone of this node and sets its treeOfBelonging to the one provided.int
compareTo(NTreeNode<K,V> other)
Returns an integer which based on weather it is negative, zero or positive determines if this node is less than, equal to or greater than the other node.
Null values are considered less than to non null values and comparison between two nulls returns 0.
Ifthis.id.compareTo(other.id)
returns 0 (equal) and the class of the value property implementsComparable
then the value properties are also compared.boolean
equals(java.lang.Object obj)
Returnstrue
if this node is equal to the other node passed.boolean
equalsSubtree(NTreeNode<K,V> other)
Returnstrue
if this subtree is equal to the provided subtree.NTreeNode<K,V>
farthestAncestor()
Returns the farthest ancestor node of this node ornull
if this node's parent isnull
.java.util.List<NTreeNode<K,V>>
findAll(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns all the nodes from the group comprising this node and its descendants for which the providedPredicate
evaluates to true.java.util.List<NTreeNode<K,V>>
findAll(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns all the nodes from the group comprising this node and its descendants for which the providedPredicate
evaluates to true.NTreeNode<K,V>
findFirst(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns the first node from the group of nodes comprised of this node and its descendants for which the passedPredicate
returns true ornull
if for no node the predicate is true.NTreeNode<K,V>
findFirstWithId(K id)
Returns the first node from the group comprising this node and its descendants that has the provided id.NTreeNode<K,V>
findFirstWithValue(V value)
Returns the first node from the group comprising this node and its descendants that has the provided value.NTreeNode<K,V>
firstChildWithValue(V value)
Returns the first child it finds that has a value that is equal to the one provided.void
forEachLevelOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a levelorder manner, meaning when traversing the nodes visit the node in level 1 and then the nodes in level 2 and so on.void
forEachLevelOrderFromBottom(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a levelorder manner but starting from the deepest level and then traversing up the levels, meaning when traversing the nodes visit the nodes in the deepest level N and then the nodes in level N-1 and so on.void
forEachNode(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in the specified traversal order.void
forEachOfLevel(int level, java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action on each node of the specified level relative to this node.void
forEachPostOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a postorder manner.void
forEachPreOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Does an action for this node and each of its descendants traversing the nodes in a preorder manner.static <K extends java.lang.Comparable<K>,V>
NTreeNode<K,V>fromJson(java.lang.String json, NTree<K,V> treeOfBelonging, java.lang.reflect.Type nodeValueType)
Returns an instance of aNTreeNode
from a JSON string.K
getId()
Returns the id of this node.NTreeNode<K,V>
getParent()
Returns theNTreeNode
that is the parent of this node.java.lang.String
getUUID()
Returns the string UUID of this node.V
getValue()
Returns the value of this node's value property.boolean
hasAncestor(NTreeNode<K,V> ancestor)
Returnstrue
if the passed node is an ancestor of this node.int
hashCode()
Returns the hashcode for this node.java.lang.Integer
height()
Returns the height of this subtree meaning the number of nodes from this node down the path to the deepest node.boolean
isBastardNode()
Returnstrue
if this node's parent isnull
and it's not the root of it's treeOfBelonging.boolean
isRoot()
Returnstrue
if this node is the root of it's treeOfBelonging.java.util.Iterator<NTreeNode<K,V>>
iterator()
Returns anIterator
to iterates over the nodes of this node and its descendants in a preorder manner.int
levelFromRoot()
Returns the level of this node relative to the root of the tree or node hierarchy it belongs to.int
levelRelativeToAncestor(NTreeNode<K,V> ancestor)
Returns the level of this node relative to the provided ancestor or -1 if this node does not have that ancestor.<R> java.util.List<R>
mapChildrenToList(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aList
of the results of applying the providedFunction
to each of this node's children.<R> java.util.Map<K,R>
mapChildrenToMap(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the providedFunction
to each of this node's children.<R> java.util.List<R>
mapToList(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the provided function to this node and its descendants.<R> java.util.List<R>
mapToList(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the provided function to this node and its descendants.java.util.List<NTreeNode<K,V>>
nodeAndConnectedNodes()
Returns aList
of nodes that include this node, its parent if it not null and its children.java.util.List<NTreeNode<K,V>>
nodesInLevel(int level)
Returns the nodes in the level relative to this node.java.util.List<NTreeNode<K,V>>
nodesUpToAncestor(NTreeNode<K,V> ancestor)
Returns aList
of this node and the nodes leading up to the ancestor plus the ancestor itself ornull
if the passed node is not an ancestor of this node.NTreeNode<K,V>
remove()
Removes this node and its descendants.java.util.Map<K,NTreeNode<K,V>>
removeAllChildren()
Removes all of this node's child nodes.java.util.List<NTreeNode<K,V>>
removeAndParentAdoptsGrandChildren()
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren).java.util.List<NTreeNode<K,V>>
removeAndParentAdoptsGrandChildren(boolean replacesDuplicates)
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren).java.util.List<NTreeNode<K,V>>
removeAndParentAdoptsGrandChildren(java.util.function.BiPredicate<NTreeNode<K,V>,NTreeNode<K,V>> bipredicate)
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren).NTreeNode<K,V>
removeChild(K id)
Removes a child of this node that has the provided id.java.util.Map<K,NTreeNode<K,V>>
removeChildren(java.util.Collection<K> ids)
Removes the child nodes of this node that whose id are in the passedCollection
of ids.java.util.Map<K,NTreeNode<K,V>>
removeChildren(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Removes the child nodes of this node for which the providedPredicate
evaluates totrue
.java.util.Map<K,NTreeNode<K,V>>
removeChildren(K... ids)
Similar toremoveChildren(Collection)
but uses a varargs parameter instead of aCollection
to pass the child ids.boolean
replaceId(K newId)
Replaces the id of this node.NTreeNode<K,V>
replaceSingleNodeWith(NTreeNode<K,V> other)
Replaces this node in a node hierarchy or tree with another node without replacing the node's descendants.NTreeNode<K,V>
replaceWith(NTreeNode<K,V> other)
Replaces this node and its descendants in a node hierarchy or tree with another node and its descendants.java.util.Map<K,NTreeNode<K,V>>
retainChildren(java.util.Collection<K> ids)
Removes all of this node's children whose id is not in the providedCollection
of ids and retains those whose id is in the collection.java.util.Map<K,NTreeNode<K,V>>
retainChildren(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Removes all of this node's children for which the providedPredicate
evaluates tofalse
and retaining those childs for which it evaluates totrue
.java.util.Map<K,NTreeNode<K,V>>
retainChildren(K... ids)
Similar toretainChildren(Collection)
but has a varargs parameter to pass the child ids.NTreeNode<K,V>
setChild(NTreeNode<K,V> node)
Sets a node as a child of this tree.boolean
setChildIfAbsent(NTreeNode<K,V> node)
Similar tosetChild(NTreeNode)
but will not replace an existing child.java.util.Map<K,NTreeNode<K,V>>
setChildren(java.util.Collection<NTreeNode<K,V>> nodes)
Sets a collection of nodes as a childs of this tree.java.util.Map<K,NTreeNode<K,V>>
setChildren(NTreeNode<K,V>... nodes)
Same assetChildren(Collection)
but accepts a varargs argument instead of aCollection
of nodes.boolean
setChildrenIfAbsent(java.util.Collection<NTreeNode<K,V>> nodes)
Similar tosetChildren(Collection)
but will not replace any existing childs.boolean
setChildrenIfAbsent(NTreeNode<K,V>... nodes)
Same assetChildrenIfAbsent(Collection)
but accepts a varargs argument instead of aCollection
of nodes.NTreeNode<K,V>
setValue(V value)
Sets the value property of this node.java.util.List<NTreeNode<K,V>>
siblingsList()
Returns aList
of this node's siblings.java.util.Map<K,NTreeNode<K,V>>
siblingsMap()
Returns aMap
of this node's siblings.int
size()
Returns the number of nodes in this subtree, which includes this node and all of its descendants.java.util.stream.Stream<NTreeNode<K,V>>
stream()
Returns aStream
of nodes that includes this node and its descendants.java.util.stream.Stream<NTreeNode<K,V>>
stream(NTreeConstants.TreeTraversalOrder traversal)
Returns aStream
of nodes that includes this node and its descendants ordered based on the traversal argument.java.lang.String
toJson()
Returns the JSON string representation of this node.java.util.List<NTreeNode<K,V>>
toList()
Similar totoList(TreeTraversalOrder)
but has a predefined traversal order of preorder.java.util.List<NTreeNode<K,V>>
toList(NTreeConstants.TreeTraversalOrder traversal)
Returns aList
of this node and its descendants.java.util.Map<K,java.util.List<NTreeNode<K,V>>>
toMapOfLists()
Returns aMap
ofList
s of this node and its descendants.java.lang.String
toString()
Returns aString
representation of this node.java.lang.String
treeGraph()
Returns a simple graphic representation of this node and its descendants in aString
.<R> java.lang.String
treeGraph(java.lang.Integer width, java.lang.Integer height, java.util.function.Function<NTreeNode<K,V>,R> dataFunction)
Returns a simple graphic representation of this node and its descendants in aString
.<R> java.lang.String
treeGraph(java.util.function.Function<NTreeNode<K,V>,R> dataFunction)
Returns a simple graphic representation of this node and its descendants in aString
.
-
-
-
Constructor Detail
-
NTreeNode
public NTreeNode(NTree<K,V> treeOfBelonging, K id)
Constructor that creates aNTreeNode
withnull
value.- Parameters:
treeOfBelonging
- theNTree
that owns this nodeid
- the id of this node
-
NTreeNode
public NTreeNode(NTree<K,V> treeOfBelonging, K id, V value)
Constructor that creates aNTreeNode
with given value. This method does not accept anull
for the value parameter. UseNTreeNode(NTree, Comparable)
if you want the value of the new node to be null.- Parameters:
treeOfBelonging
- theNTree
that owns this nodeid
- the id of this nodevalue
- the value of this node. Cannot benull
-
-
Method Detail
-
replaceId
public boolean replaceId(K newId)
Replaces the id of this node.- Parameters:
newId
- the id that replaces the existing id- Returns:
true
if it replaces the id, otherwisefalse
. Reasons it does not replace the id are:
• The new id is equal to the existing id.
• The node has a sibling that already has that id
-
getId
public K getId()
Returns the id of this node.- Returns:
- the id of this node
-
setValue
public NTreeNode<K,V> setValue(V value)
Sets the value property of this node.- Parameters:
value
- the value for this node's value property. It can benull
.
-
getValue
public V getValue()
Returns the value of this node's value property.- Returns:
- the value of this node's value property
-
getParent
public NTreeNode<K,V> getParent()
Returns theNTreeNode
that is the parent of this node. Could benull
.- Returns:
- the
NTreeNode
that is the parent of this node
-
getUUID
public java.lang.String getUUID()
Returns the string UUID of this node. Each node has a unique UUID which is automatically generated when a node is instantiated or cloned. Serialization and deserialization to and from JSON does not create a new UUID.- Returns:
- the string UUID unique to this tree
-
replaceSingleNodeWith
public NTreeNode<K,V> replaceSingleNodeWith(NTreeNode<K,V> other)
Replaces this node in a node hierarchy or tree with another node without replacing the node's descendants. The node passed will not be changed and instead a clone of it will be used.- Parameters:
other
- the node to replace this node- Returns:
- this node if replaced or
null
if it did not replace this node. Reasons for not replacing this node can be one of the following:
• The node to replace this node is this node.
• This node is not a root of aNTree
and it's parent is null.
• This node has a sibling node that has the same id as the replacement node.
-
replaceWith
public NTreeNode<K,V> replaceWith(NTreeNode<K,V> other)
Replaces this node and its descendants in a node hierarchy or tree with another node and its descendants. The node passed will not be changed and instead a clone of it and its descendants will be used.- Parameters:
other
- the node to replace this node with its descendants.- Returns:
- this node if replaced or
null
if not replaced. Reasons for not replacing this node can be one of the following:
• The node to replace this node is this node.
• This node is not a root of aNTree
and it's parent is null.
• This node has a sibling node that has the same id as the replacement node.
-
remove
public NTreeNode<K,V> remove()
Removes this node and its descendants.- Returns:
- this node if removed or
null
if not removed. If this node's parent is null but this node is not a root of aNTree
it will not be removed andnull
will be returned.
-
removeAndParentAdoptsGrandChildren
public java.util.List<NTreeNode<K,V>> removeAndParentAdoptsGrandChildren(java.util.function.BiPredicate<NTreeNode<K,V>,NTreeNode<K,V>> bipredicate)
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren).- Parameters:
bipredicate
- aBiPredicate
that if evaluates totrue
then siblings of this node that have the same id as the adopted children are replaced by the children with the same id. If it evaluates tofalse
then the children are removed and the uncle with the same id remains. The first argument of theBiPredicate
is for the node's child and the second for the node's sibling.- Returns:
- a list containing this node if it was removed plus any node that was
replaced, if any or
null
if it was not removed
-
removeAndParentAdoptsGrandChildren
public java.util.List<NTreeNode<K,V>> removeAndParentAdoptsGrandChildren()
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren). If a child of this node has the same id as a sibling of this node, the child is removed.- Returns:
- a list containing the node that was removed plus any node that was
replaced, if any or
null
if it was not removed
-
removeAndParentAdoptsGrandChildren
public java.util.List<NTreeNode<K,V>> removeAndParentAdoptsGrandChildren(boolean replacesDuplicates)
Removes this node from a tree or node hierarchy and it's parent adopts it's children (it's parent grandchildren). If a child of this node has the same id as a sibling of node and this nodereplacesDuplicates argument istrue
the sibling is removed, but if replacesDuplicates argument isfalse
the child is removed.- Returns:
- a list containing the node that was removed plus any node that was
replaced, if any or
null
if it was not removed
-
addNewChildren
public NTreeNode<K,V> addNewChildren(NTreeNode<K,V>... children)
Adds new child nodes to this node. The nodes to be added as childs must have a parent that isnull
or they will not be added. If two or more childs have the same id then only the first one will be added.- Parameters:
children
- a varargs ofNTreeNode
to be added as childs of this node- Returns:
- this node
-
setChild
public NTreeNode<K,V> setChild(NTreeNode<K,V> node)
Sets a node as a child of this tree. If this node has a child with the same id as the node passed then the child will be replaced. The passed node will be left unchanged and a clone of it and its descendants will be used instead.- Parameters:
node
- the node to set as a child of this node- Returns:
null
if the node set as a child did not replace any existing child, otherwise returns the replaced child- Throws:
java.lang.RuntimeException
- if trying to set already existing child
-
setChildren
public java.util.Map<K,NTreeNode<K,V>> setChildren(java.util.Collection<NTreeNode<K,V>> nodes)
Sets a collection of nodes as a childs of this tree. If this node has a child with the same id as one of the node passed then the child will be replaced. The passed nodes will be left unchanged and a clone of them and their descendants will be used instead.- Parameters:
nodes
- the nodes to set as a children of this node- Returns:
- a
Map
of nodes that where replaced, where the keys are their ids
-
setChildren
public java.util.Map<K,NTreeNode<K,V>> setChildren(NTreeNode<K,V>... nodes)
Same assetChildren(Collection)
but accepts a varargs argument instead of aCollection
of nodes.- Parameters:
nodes
- a varargs ofNTreeNode
to set as children of this node- Returns:
- a
Map
of nodes that where replaced, where the keys are their ids
-
setChildIfAbsent
public boolean setChildIfAbsent(NTreeNode<K,V> node)
Similar tosetChild(NTreeNode)
but will not replace an existing child.- Parameters:
node
- the node to set as a child of this node- Returns:
true
if the child was set orfalse
otherwise.false
means that this node had already a child with the same id
-
setChildrenIfAbsent
public boolean setChildrenIfAbsent(java.util.Collection<NTreeNode<K,V>> nodes)
Similar tosetChildren(Collection)
but will not replace any existing childs.- Parameters:
nodes
- aCollection
of nodes to set as a children of this node- Returns:
true
if it added all nodes passed as children
-
setChildrenIfAbsent
public boolean setChildrenIfAbsent(NTreeNode<K,V>... nodes)
Same assetChildrenIfAbsent(Collection)
but accepts a varargs argument instead of aCollection
of nodes.- Parameters:
nodes
- a varargs ofNTreeNode
to set as children of this node- Returns:
true
if it added all nodes passed as children
-
childWithId
public NTreeNode<K,V> childWithId(K id)
Returns the child node that matches the passed id.- Parameters:
id
- the id of the child to return- Returns:
- the child node that matches the provided id or
null
if this node does not have a child with that id
-
firstChildWithValue
public NTreeNode<K,V> firstChildWithValue(V value)
Returns the first child it finds that has a value that is equal to the one provided. The traversal order between the childs of this node is not ordered by default. This can be changed by configuring this node's treeOfBelonging usingNTree.useNaturalOrdering()
orNTree.useCustomOrdering(java.util.function.BiFunction)
.- Parameters:
value
- the value of the child node to return- Returns:
- the first child node that it finds that has a value equal to the
one provided or
null
if no child has that value.
-
childrenList
public java.util.List<NTreeNode<K,V>> childrenList()
Returns aList
of this node's children.- Returns:
- a
List
of this node's children
-
childrenList
public java.util.List<NTreeNode<K,V>> childrenList(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns aList
of this node's children for which the providedPredicate
evaluates totrue
.- Parameters:
predicate
- thePredicate
that is used to filter which childs to return- Returns:
- a
List
of this node's children for which the providedPredicate
evaluates totrue
-
childrenList
public java.util.List<NTreeNode<K,V>> childrenList(java.util.Collection<K> ids)
Returns aList
of this node's children whose ids are included in the passedCollection
of ids.- Parameters:
a
-Collection
of ids used to filter which childs to return- Returns:
- a
List
of this node's children whose ids are included in the passedCollection
of ids
-
childrenList
public java.util.List<NTreeNode<K,V>> childrenList(K... ids)
Similar tochildrenList(Collection)
but has a varargs parameter instead of aCollection
of nodes- Parameters:
ids
- the varargs of ids- Returns:
- a
List
of this node's children whose ids are included in the passed varargs ids parameter
-
childrenMap
public java.util.Map<K,NTreeNode<K,V>> childrenMap()
Returns aMap
of this node's children. The Map keys are the children's ids.- Returns:
- a
Map
of this node's children. The Map keys are the children's ids.
-
childrenMap
public java.util.Map<K,NTreeNode<K,V>> childrenMap(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns aMap
of this node's children for which the providedPredicates
evaluates totrue
. The Map keys are the children's ids.- Returns:
- a
Map
of this node's children for which the providedPredicates
evaluates totrue
. The Map keys are the children's ids.
-
childrenMap
public java.util.Map<K,NTreeNode<K,V>> childrenMap(java.util.Collection<K> ids)
Returns aMap
of this node's children that have ids that are in the providedCollection
of ids. The Map keys are the children's ids.- Returns:
- a
Map
of this node's children that have ids that are in the providedCollection
of ids. The Map keys are the children's ids.
-
childrenMap
public java.util.Map<K,NTreeNode<K,V>> childrenMap(K... ids)
Similar tochildrenMap(Collection)
but instead of having aCollection
as parameter it uses a varargs parameter.- Returns:
- a
Map
of this node's children that have ids that are in the provided varargs of ids. The Map keys are the children's ids.
-
removeChild
public NTreeNode<K,V> removeChild(K id)
Removes a child of this node that has the provided id.- Parameters:
id
- the id of the child node to remove- Returns:
- the removed node or
null
if this node has no child with the provided id
-
removeChildren
public java.util.Map<K,NTreeNode<K,V>> removeChildren(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Removes the child nodes of this node for which the providedPredicate
evaluates totrue
.- Parameters:
predicate
- thePredicate
which if true will make a child node of this node be removed- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
removeChildren
public java.util.Map<K,NTreeNode<K,V>> removeChildren(java.util.Collection<K> ids)
Removes the child nodes of this node that whose id are in the passedCollection
of ids.- Parameters:
ids
- aCollection
of the ids of the child nodes to remove- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
removeChildren
public java.util.Map<K,NTreeNode<K,V>> removeChildren(K... ids)
Similar toremoveChildren(Collection)
but uses a varargs parameter instead of aCollection
to pass the child ids.- Parameters:
ids
- a vararg of the ids of the child nodes to remove- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
removeAllChildren
public java.util.Map<K,NTreeNode<K,V>> removeAllChildren()
Removes all of this node's child nodes.- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
retainChildren
public java.util.Map<K,NTreeNode<K,V>> retainChildren(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Removes all of this node's children for which the providedPredicate
evaluates tofalse
and retaining those childs for which it evaluates totrue
.- Parameters:
predicate
- thePredicate
which when evaluates tofalse
makes the child be removed.- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
retainChildren
public java.util.Map<K,NTreeNode<K,V>> retainChildren(java.util.Collection<K> ids)
Removes all of this node's children whose id is not in the providedCollection
of ids and retains those whose id is in the collection.- Parameters:
ids
- aCollection
of ids of the childs to be removed.- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
retainChildren
public java.util.Map<K,NTreeNode<K,V>> retainChildren(K... ids)
Similar toretainChildren(Collection)
but has a varargs parameter to pass the child ids.- Parameters:
ids
- a varargs of ids of the child nodes to retain- Returns:
- a
Map
of the child nodes removed. The keys of the map are the ids of the child nodes.
-
childrenSize
public int childrenSize()
Returns the number of children this node has.- Returns:
- the number of children this node has
-
childrenIds
public java.util.List<K> childrenIds()
Returns aList
of the ids of this node's children.- Returns:
- a
List
of the ids of this node's children
-
childrenValues
public java.util.List<V> childrenValues()
Returns aList
of the values of this node's children.- Returns:
- a
List
of the values of this node's children
-
mapChildrenToList
public <R> java.util.List<R> mapChildrenToList(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aList
of the results of applying the providedFunction
to each of this node's children.- Type Parameters:
R
- the return type of the passed function. Java can infer it.- Parameters:
function
- theFunction
whose result of being applied to each child node is an item in the returnedList
- Returns:
- a
List
of the results of applying the mappingFunction
to each of this node's children
-
mapChildrenToMap
public <R> java.util.Map<K,R> mapChildrenToMap(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the providedFunction
to each of this node's children. The map keys are the children ids.- Type Parameters:
R
- the return type of the passed function. Java can infer it.- Parameters:
function
- theFunction
whose result of being applied to each child node is a value of an entry in the returnedMap
- Returns:
- a
Map
of the results of applying the mappingFunction
to each of this node's children. The keys of the map are the child ids and the values are the result of the mapping function.
-
childrenIdsValuesMap
public java.util.Map<K,V> childrenIdsValuesMap()
Returns aMap
of where the keys are the ids of this node's children and the values are their values.- Returns:
- a
Map
of where the keys are the ids of this node's children and the values are their values
-
siblingsMap
public java.util.Map<K,NTreeNode<K,V>> siblingsMap()
Returns aMap
of this node's siblings. The keys of the map are the siblings ids. If this node is a root or it's parent isnull
thennull
is returned.- Returns:
- a
Map
of this node's siblings. The keys of the map are the siblings ids.
-
siblingsList
public java.util.List<NTreeNode<K,V>> siblingsList()
Returns aList
of this node's siblings.- Returns:
- a
List
of this node's siblings.
-
cloneSingleNode
public NTreeNode<K,V> cloneSingleNode(NTree<K,V> treeOfBelonging)
Returns a clone of this node and sets its treeOfBelonging to the one provided. By default the node's value id copied using simple serialization. This can be changed if the tree is configured withNTree.nodeValueCloningUsesCopyConstructor()
orNTree.nodeValueCloningUsesSerialization(Type)
.
The returned clone does not have any parent or children.- Parameters:
treeOfBelonging
- the tree that owns the returned clone- Returns:
- a clone of this node without any parent or children
-
cloneSingleNode
public NTreeNode<K,V> cloneSingleNode()
Returns a clone of this node and sets its treeOfBelonging to the one this node has. By default the node's value id copied using simple serialization. This can be changed if the tree is configured withNTree.nodeValueCloningUsesCopyConstructor()
orNTree.nodeValueCloningUsesSerialization(Type)
.
The returned clone does not have any parent or children.- Parameters:
treeOfBelonging
- the tree that owns the returned clone- Returns:
- a clone of this node without any parent or children
-
clone
public NTreeNode<K,V> clone(NTree<K,V> treeOfBelonging)
Returns a clone of this node and its descendant. The parent of the returned clone isnull
. The treeOfBelonging of the returned clone and its descendant will be set to the provided treeOfBelonging. The parent of the returned clone will benull
.- Parameters:
treeOfBelonging
- the tree that owns the returned clone and its descendants- Returns:
- a Returns a clone of this node and its descendant.
-
clone
public NTreeNode<K,V> clone()
Returns a clone of this node and its descendant. The parent of the returned clone isnull
. The treeOfBelonging of the returned clone and its descendant will be the same as this node's treeOfBelonging. The parent of the returned clone will benull
.- Overrides:
clone
in classjava.lang.Object
- Returns:
- a Returns a clone of this node and its descendant.
-
forEachPreOrder
public void forEachPreOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Does an action for this node and each of its descendants traversing the nodes in a preorder manner.- Parameters:
action
- theConsumer
that will execute an action for this node and each of its descendants
-
forEachPostOrder
public void forEachPostOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a postorder manner.- Parameters:
action
- theConsumer
that will execute an action for this node and each of its descendants
-
forEachOfLevel
public void forEachOfLevel(int level, java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action on each node of the specified level relative to this node.- Parameters:
level
- the level relative to this node. This node is level 1, its children are level 2 and so on.action
- theConsumer
that will execute an action for the nodes at the specified level relative to this node- Throws:
java.lang.RuntimeException
- if the provided level is less than 1
-
forEachLevelOrder
public void forEachLevelOrder(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a levelorder manner, meaning when traversing the nodes visit the node in level 1 and then the nodes in level 2 and so on.- Parameters:
action
- theConsumer
that will execute an action for this node and each of its descendants
-
forEachLevelOrderFromBottom
public void forEachLevelOrderFromBottom(java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in a levelorder manner but starting from the deepest level and then traversing up the levels, meaning when traversing the nodes visit the nodes in the deepest level N and then the nodes in level N-1 and so on.- Parameters:
action
- theConsumer
that will execute an action for this node and each of its its descendants
-
forEachNode
public void forEachNode(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Consumer<NTreeNode<K,V>> action)
Performs an action for this node and each of its descendants traversing the nodes in the specified traversal order.- Parameters:
traversal
- theNTreeConstants.TreeTraversalOrder
enum that determines the traversal order.action
- theConsumer
that will execute an action for this node and its each of its descendants
-
height
public java.lang.Integer height()
Returns the height of this subtree meaning the number of nodes from this node down the path to the deepest node.- Returns:
- the height of this subtree
-
size
public int size()
Returns the number of nodes in this subtree, which includes this node and all of its descendants.- Returns:
- the number of nodes in this subtree, which includes this node and all of its descendants
-
isRoot
public boolean isRoot()
Returnstrue
if this node is the root of it's treeOfBelonging.- Returns:
true
if this node is the root of it's treeOfBelonging
-
isBastardNode
public boolean isBastardNode()
Returnstrue
if this node's parent isnull
and it's not the root of it's treeOfBelonging.- Returns:
true
if this node's parent isnull
and it's not the root of it's treeOfBelonging
-
levelFromRoot
public int levelFromRoot()
Returns the level of this node relative to the root of the tree or node hierarchy it belongs to.- Returns:
- the level of this node relative to the root of the tree or node hierarchy it belongs to
-
levelRelativeToAncestor
public int levelRelativeToAncestor(NTreeNode<K,V> ancestor)
Returns the level of this node relative to the provided ancestor or -1 if this node does not have that ancestor.- Returns:
- the level of this node relative to the provided ancestor or -1 if this node does not have that ancestor
-
toMapOfLists
public java.util.Map<K,java.util.List<NTreeNode<K,V>>> toMapOfLists()
Returns aMap
ofList
s of this node and its descendants. The map keys are the node ids and the values are lists of nodes that have the same id.- Returns:
- a
Map
ofList
s of this node and its descendants. The map keys are the node ids and the values are lists of nodes that have the same id.
-
toList
public java.util.List<NTreeNode<K,V>> toList(NTreeConstants.TreeTraversalOrder traversal)
Returns aList
of this node and its descendants.- Parameters:
traversal
- theNTreeConstants.TreeTraversalOrder
enum that determines the traversal order used to traverse the nodes and create the list- Returns:
- a
List
of this node and its descendants
-
toList
public java.util.List<NTreeNode<K,V>> toList()
Similar totoList(TreeTraversalOrder)
but has a predefined traversal order of preorder.- Returns:
- a
List
of this node and its descendants.
-
nodeAndConnectedNodes
public java.util.List<NTreeNode<K,V>> nodeAndConnectedNodes()
Returns aList
of nodes that include this node, its parent if it not null and its children.- Returns:
- a
List
of nodes that include this node, its parent if it not null and its children
-
farthestAncestor
public NTreeNode<K,V> farthestAncestor()
Returns the farthest ancestor node of this node ornull
if this node's parent isnull
.- Returns:
- the farthest ancestor node of this node or
null
if this node's parent isnull
-
hasAncestor
public boolean hasAncestor(NTreeNode<K,V> ancestor)
Returnstrue
if the passed node is an ancestor of this node.- Parameters:
ancestor
- the node to check if it is an ancestor of this node- Returns:
true
if the passed node is an ancestor of this node
-
nodesUpToAncestor
public java.util.List<NTreeNode<K,V>> nodesUpToAncestor(NTreeNode<K,V> ancestor)
Returns aList
of this node and the nodes leading up to the ancestor plus the ancestor itself ornull
if the passed node is not an ancestor of this node.- Parameters:
ancestor
- the node that is an ancestor of this node- Returns:
- a
List
of this node and the nodes leading up to the ancestor plus the ancestor itself ornull
if the passed node is not an ancestor of this node
-
nodesInLevel
public java.util.List<NTreeNode<K,V>> nodesInLevel(int level)
Returns the nodes in the level relative to this node. This node would be level 1, its children level 2 and so on.- Parameters:
level
- the level relative to this node to get the nodes from- Returns:
- a
List
of the nodes at the specified level relative to this node - Throws:
java.lang.RuntimeException
- if the passed level is less than 1
-
stream
public java.util.stream.Stream<NTreeNode<K,V>> stream()
Returns aStream
of nodes that includes this node and its descendants.- Returns:
- a
Stream
of nodes that includes this node and its descendants
-
stream
public java.util.stream.Stream<NTreeNode<K,V>> stream(NTreeConstants.TreeTraversalOrder traversal)
Returns aStream
of nodes that includes this node and its descendants ordered based on the traversal argument.- Parameters:
traversal
- theNTreeConstants.TreeTraversalOrder
enum that determines the order of the nodes in the stream- Returns:
- a
Stream
of nodes that includes this node and its descendants
-
mapToList
public <R> java.util.List<R> mapToList(java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the provided function to this node and its descendants. The list is ordered based on the preorder traversal of this node and its descendants. The keys of the map are the nodes ids and the values are the result of the passed function for each node.- Type Parameters:
R
- the return type of the passed function. Java can infer it.- Parameters:
function
- theFunction
that is applied to this node and its descendants and whose results are the values of the returned map- Returns:
- a
List
-
mapToList
public <R> java.util.List<R> mapToList(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Function<NTreeNode<K,V>,R> function)
Returns aMap
of the results of applying the provided function to this node and its descendants. The list is ordered based on the traversal argument which determines the traversal of this node and its descendants. The keys of the map are the nodes ids and the values are the result of the passed function for each node.- Type Parameters:
R
- the return type of the passed function. Java can infer it.- Parameters:
function
- theFunction
that is applied to this node and its descendants and whose results are the values of the returned map- Returns:
- a
List
-
findAll
public java.util.List<NTreeNode<K,V>> findAll(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns all the nodes from the group comprising this node and its descendants for which the providedPredicate
evaluates to true. The order of the list is determined by a preorder traversal of this node and its descendants.- Parameters:
predicate
- thePredicate
used to filter this node and its descendants- Returns:
- a
List
of nodes for which the passed predicate evaluates to true
-
findAll
public java.util.List<NTreeNode<K,V>> findAll(NTreeConstants.TreeTraversalOrder traversal, java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns all the nodes from the group comprising this node and its descendants for which the providedPredicate
evaluates to true. The order of the list is determined by a the passed traversal.- Parameters:
traversal
- theNTreeConstants.TreeTraversalOrder
that determines the order of the nodes in the returned listpredicate
- thePredicate
used to filter this node and its descendants- Returns:
- a
List
of nodes for which the passed predicate evaluates to true
-
findFirst
public NTreeNode<K,V> findFirst(java.util.function.Predicate<NTreeNode<K,V>> predicate)
Returns the first node from the group of nodes comprised of this node and its descendants for which the passedPredicate
returns true ornull
if for no node the predicate is true. The search is done in a preorder manner.- Parameters:
predicate
- thePredicate
that if true then returns the node for which it was evaluated- Returns:
- the found node or
null
if not match was found
-
findFirstWithId
public NTreeNode<K,V> findFirstWithId(K id)
Returns the first node from the group comprising this node and its descendants that has the provided id.- Parameters:
id
- the id of the node to find- Returns:
- the found node or
null
if not found
-
findFirstWithValue
public NTreeNode<K,V> findFirstWithValue(V value)
Returns the first node from the group comprising this node and its descendants that has the provided value.- Parameters:
value
- the value of the node to find- Returns:
- the found node or
null
if not found
-
equalsSubtree
public boolean equalsSubtree(NTreeNode<K,V> other)
Returnstrue
if this subtree is equal to the provided subtree. Two subtrees are equal if their node hierarchy is the same and the corresponding nodes in each hierarchy are equal.- Returns:
true
if this subtree is equal to the provided subtree
-
treeGraph
public <R> java.lang.String treeGraph(java.lang.Integer width, java.lang.Integer height, java.util.function.Function<NTreeNode<K,V>,R> dataFunction)
Returns a simple graphic representation of this node and its descendants in aString
.- Type Parameters:
R
- the return type of the provided dataFunction parameter. Java can imply it.- Parameters:
width
- the width factor. Ifnull
or less than 1 then it defaults to 4.height
- the height factor. Ifnull
or less than 1 then it defaults to 2.dataFunction
- theFunction
whose result is displayed next to each node's id. Ifnull
then no data is displayed next to each node's id.- Returns:
- a
String
that when printed forms a simple graphic representation of this node and its descendants
-
treeGraph
public <R> java.lang.String treeGraph(java.util.function.Function<NTreeNode<K,V>,R> dataFunction)
Returns a simple graphic representation of this node and its descendants in aString
.- Type Parameters:
R
- the return type of the provided dataFunction parameter. Java can imply it.- Parameters:
dataFunction
- theFunction
whose result is displayed next to each node's id. Ifnull
then no data is displayed next to each node's id.- Returns:
- a
String
that when printed forms a simple graphic representation of this node and its descendants
-
treeGraph
public java.lang.String treeGraph()
Returns a simple graphic representation of this node and its descendants in aString
.- Returns:
- a
String
that when printed forms a simple graphic representation of this node and its descendants
-
toJson
public java.lang.String toJson()
Returns the JSON string representation of this node. This does not include its parent and treeOfBelonging.- Returns:
- the JSON string representation of this node. This does not include its parent and treeOfBelonging.
-
fromJson
public static <K extends java.lang.Comparable<K>,V> NTreeNode<K,V> fromJson(java.lang.String json, NTree<K,V> treeOfBelonging, java.lang.reflect.Type nodeValueType)
Returns an instance of aNTreeNode
from a JSON string.- Type Parameters:
K
- the type of the node idV
- the type of the node value- Parameters:
json
- the JSON string representation of anNTreeNode
treeOfBelonging
- theNTree
that is to be the owner of the creaed nodenodeValueType
- the type of the node values- Returns:
- an
NTreeNode
-
iterator
public java.util.Iterator<NTreeNode<K,V>> iterator()
Returns anIterator
to iterates over the nodes of this node and its descendants in a preorder manner.
-
compareTo
public int compareTo(NTreeNode<K,V> other)
Returns an integer which based on weather it is negative, zero or positive determines if this node is less than, equal to or greater than the other node.
Null values are considered less than to non null values and comparison between two nulls returns 0.
Ifthis.id.compareTo(other.id)
returns 0 (equal) and the class of the value property implementsComparable
then the value properties are also compared.
-
hashCode
public int hashCode()
Returns the hashcode for this node. The hashcode is calculated using the id and value of this node.- Overrides:
hashCode
in classjava.lang.Object
- Returns:
- an
int
that is the hashcode for this node
-
equals
public boolean equals(java.lang.Object obj)
Returnstrue
if this node is equal to the other node passed. Two nodes are considered equal if their ids are equal and their values are also equal.- Overrides:
equals
in classjava.lang.Object
- Returns:
true
if this node's id is equal to the other node's id and this node's value is equal to the other node's value.
-
toString
public java.lang.String toString()
Returns aString
representation of this node. The parent field is replaced by parent_id with a string representation of of the parent id. The the children field is replaced by children_ids with a list representation of the children ids.- Overrides:
toString
in classjava.lang.Object
- Returns:
- the
String
representation of this node
-
-


| < Day Day Up > |
11.2. Lisp Primitive FunctionsNow that you've seen how to write a working command, we'll discuss Lisp's primitive functions. These are the building blocks from which you'll build your functions. As mentioned above, Lisp uses functions where other languages would use operators, that is, for arithmetic, comparison, and logic. Table 11-3 shows some Lisp primitive functions that are equivalent to these operators.
All the arithmetic functions except 1+, 1-, and % can take arbitrarily many arguments, as can and and or. An arithmetic function returns floating point values only if at least one argument is a floating point number, so for example, (/ 7.0 4) returns 1.75, and (/ 7 4) returns 1. Notice that integer division truncates the remainder. It may seem inefficient or syntactically ugly to use functions for everything. However, one of the main merits of Lisp is that the core of the language is small and easy to interpret efficiently. In addition, the syntax is not as much of a problem if you have support tools such as Emacs's Lisp modes to help you. 11.2.1 Statement BlocksWe have seen that a statement block can be defined using the let function. We also saw that while and save-excursion include statement blocks. Other important constructs also define statement blocks: progn and other forms of let. progn, the most basic, has the form: (progn statement-block) progn is a simple way of making a block of statements look like a single one, somewhat like the curly braces of Java or the begin and end of Pascal. The value returned by progn is the value returned by the last statement in the block. progn is especially useful with control structures like if (see the following discussion) that, unlike while, do not include statement blocks. The let function has other forms as well. The simplest is: (let (var1 var2 ...)
statement-block) In this case, instead of a list of (var value) pairs, there is simply a list of variable names. As with the other form of let, these become local variables accessible in the statement block. However, instead of initializing them to given values, they are all just initialized to nil. You can actually mix both forms within the same let statement, for example: (let (var1 (var2 value2) var3 ...) statement-block) In the form of let we saw first, the initial values for the local variables can be function calls (remember that all functions return values). All such functions are evaluated before any values are assigned to variables. However, there may be cases in which you want the values of some local variables to be available for computing the values of others. This is where let*, the final version of let, comes in. let* steps through its assignments in order, assigning each local variable a value before moving on to the next. For example, let's say we want to write a function goto-percent that allows you to go to a place in the current buffer expressed as a percentage of the text in the buffer. Here is one way to write this function: (defun goto-percent (pct) (interactive "nGoto percent: ") (let* ((size (point-max)) (charpos (/ (* size pct) 100))) (goto-char charpos))) As we saw earlier, the interactive function is used to prompt users for values of arguments. In this case, it prompts for the integer value of the argument pct. Then the let* function initializes size to the size of the buffer in characters, then uses that value to compute the character position charpos that is pct (percent) of the buffer's size. Finally, the call of goto-char causes point to be moved to that character position in the current window. The important thing to notice is that if we had used let instead of let*, the value of size would not be available when computing the value of charpos. let* can also be used in the (var1 var2 ...) format, just like let, but there wouldn't be any point in doing so. We should also note that a more efficient way to write goto-percent is this: (defun goto-percent (pct) (interactive "nPercent: ") (goto-char (/ (* pct (point-max)) 100))) 11.2.2 Control StructuresWe already saw that the while function acts as a control structure like similar statements in other languages. There are two other important control structures in Lisp: if and cond. The if function has the form: (if condition true-case false-block) Here, the condition is evaluated; if it is non-nil, true-case is evaluated; if nil, false-block is evaluated. Note that true-case is a single statement whereas false-block is a statement block; false-block is optional. As an example, let's suppose we're writing a function that performs some complicated series of edits to a buffer and then reports how many changes it made. We're perfectionists, so we want the status report to be properly pluralized, that is to say "made 53 changes" or "made 1 change." This is a common enough programming need that we decide to write a general-purpose function to do it so that we can use it in other projects too. The function takes two arguments: the word to be pluralized (if necessary) and the count to be displayed (which determines whether it's necessary). (defun pluralize (word count) (if (= count 1) word (concat word "s"))) The condition in the if clause tests to see if count is equal to 1. If so, the first statement gets executed. Remember that the "true" part of the if function is only one statement, so progn would be necessary to make a statement block if we wanted to do more than one thing. In this case, we have the opposite extreme; our "true" part is a single variable, word. Although this looks strange, it is actually a very common Lisp idiom and worth getting used to. When the condition block is true, the value of word is evaluated, and this value becomes the value of the entire if statement. Because that's the last statement in our function, it is the value returned by pluralize. Note that this is exactly the result we want when count is 1: the value of word is returned unchanged. The remaining portion of the if statement is evaluated when the condition is false, which is to say, when count has a value other than 1. This results in a call to the built-in concat function, which concatenates all its arguments into a single string. In this case it adds an "s" at the end of the word we've passed in. Again, the result of this concatenation becomes the result of the if statement and the result of our pluralize function. If you type it in and try it out, you'll see results like this: (pluralize "goat" 5) "goats" (pluralize "change" 1) "change" Of course, this function can be tripped up easily enough. You may have tried something like this already: (pluralize "mouse" 5) "mouses" To fix this, we'd need to be able to tell the function to use an alternate plural form for tricky words. But it would be nice if the simple cases could remain as simple as they are now. This is a good opportunity to use an optional parameter. If necessary, we supply the plural form to use; if we don't supply one, the function acts as it did in its first incarnation. Here's how we'd achieve that: (defun pluralize (word count &optional plural) (if (= count 1) word (if (null plural) (concat word "s") plural))) The "else" part of our code has become another if statement. It uses the null function to check whether we were given the plural parameter or not. If plural was omitted, it has the value nil and the null function returns t if its argument is nil. So this logic reads "if b was missing, just add an s to word; otherwise return the special plural value we were given." This gives us results like this: (pluralize "mouse" 5) "mouses" (pluralize "mouse" 5 "mice") "mice" (pluralize "mouse" 1 "mice") "mouse" A more general conditional control structure is the cond function, which has the following form: (cond
(condition1 statement-block1)
(condition2 statement-block2)
...) Java and Perl programmers can think of this as a sequence of if then else if then else if . . . , or as a kind of generalized switch statement. The conditions are evaluated in order, and when one of them evaluates to non-nil, the corresponding statement block is executed; the cond function terminates and returns the last value in that statement block.[5]
We can use cond to give a more folksy feel to our hypothetical status reporter now that it's pluralizing nicely. Instead of reporting an actual numeric value for the number of changes, we could have it say no, one, two, or many as appropriate. Again we'll write a general function to do this: (defun how-many (count) (cond ((zerop count) "no") ((= count 1) "one") ((= count 2) "two") (t "many"))) The first conditional expression introduces a new primitive Lisp function, zerop. It checks whether its argument is zero, and returns t (true) when it is. So when count is zero, the cond statement takes this first branch, and our function returns the value no. This strange function name bears a little explanation. It is pronounced "zero-pee" and is short for "zero predicate." In the realm of mathematical logic from which Lisp evolved, a predicate is a function that returns true or false based on some attribute of its argument. Lisp has a wide variety of similar predicate functions, with structurally related names. When you run into the next one, you'll understand it. (Of course, you might now expect the null function we introduced in the previous example to be called "nilp" instead. Nobody's perfectly consistent.) The next two conditional expressions in the cond statement check if count is 1 or 2 and cause it to return "one" or "two" as appropriate. We could have written the first one using the same structure, but then we'd have missed out on an opportunity for a digression into Lisp trivia! The last conditional expression is simply the atom t (true), which means its body is executed whenever all the preceding expressions failed. It returns the value many. Executing this function gives us results like these: (how-many 1) "one" (how-many 0) "no" (how-many 3) "many" Combining these two helper functions into a mechanism to report the change count for our fancy command is easy. (defun report-change-count (count) (message "Made %s %s." (how-many count) (pluralize "change" count))) We get results like these: (report-change-count 0) "Made no changes." (report-change-count 1) "Made one change." (report-change-count 1329) "Made many changes." |
| < Day Day Up > |


Controls
Pan
Select
Select random
Toggle Orbit
Render
Points
Sprites
Text
3D
Sequences
Color by
Default
Label


?The
New
York
copyright
reserved
botanical
Garden
ANNOTATION
LABEL
Oenothera
rosea
L'Her
ex
Ait
P.H.
Raven
&
D.R.
Parnell
1970
THE
NEW
YORK
BOTANICAL
GARDEN
EXPLORATION
OF.
JAMAICA
VICINITY
OF
CINCHONA
NEW
YORK
BOTANICAL
GARDEN
ALEXANDRINA
TAYLOR,
COLLECTOR
1909
01447755
01447755
Legend -
Level of confidence that token is an accurately-transcribed word
extremely low
very low
low
undetermined
medium
high
very high


Problem 3. Rectangle area
Write an expression that calculates rectangle’s area by given width and height.
Please enter width:
Please enter height:
Submit
Rectangle area:


Support
While Quicksilver's flexibility may seem daunting at first, the Quicksilver community is invaluable for new users. Please drop in and learn all the ways it can help you.
Forums - Get hints, help, and ideas from other users. Suggestions and comments are always welcome.
Bug Reporter - Report and track issues with Quicksilver.
IRC Chat - Chat with other users. Requires an IRC client.
Creating Quicksilver has been a pleasure, and we hope you find it useful. Enjoy! —The Blacktree Team


Module: Sunspot::Query::Filter
- Included in:
- Connective::Abstract, Restriction::Base
- Defined in:
- sunspot/lib/sunspot/query/filter.rb
Instance Method Summary (collapse)
-
- (Object) tag
Generate and return a tag that can be attached to this restriction, for use with multiselect faceting.
-
- (Object) to_filter_query
Express this filter as an :fq parameter; i.e., the boolean phrase, maybe prefixed by local params.
Instance Method Details
- (Object) tag
Generate and return a tag that can be attached to this restriction, for use with multiselect faceting. This needs to be unique, but doesn’t really need to be human-readable, so just generate a string based on the hash of the boolean phrase.
21 22 23 |
# File 'sunspot/lib/sunspot/query/filter.rb', line 21 def tag @tag ||= to_boolean_phrase.hash.abs.to_s(36) end |
- (Object) to_filter_query
Express this filter as an :fq parameter; i.e., the boolean phrase, maybe prefixed by local params.
9 10 11 12 13 |
# File 'sunspot/lib/sunspot/query/filter.rb', line 9 def to_filter_query if tagged? then "{!tag=#{tag}}#{to_boolean_phrase}" else to_boolean_phrase end end |


--- title: "1.1 — The Tools of Microeconomics — Class Content" citeproc: false bibliography: ../../static/bib/references.bib csl: ../../static/bib/chicago-syllabus-no-bib.csl output: blogdown::html_page: template: ../../pandoc/toc-title_html.template toc: true editor_options: chunk_output_type: console ---
Welcome to ECON 306 - Microeconomic Analysis! Today’s lesson will be an introduction to the course and the tools we use in microeconomics.
If you have not done so, please watch my welcome video, take my survey, join our class Slack channel, and read the important items, which can be found in the START HERE
menu item in the course’s Blackboard site.I would link to them all here, but this website is public on the internet, so I am ensuring only real enrolled students can access these via Blackboard!
The live class Zoom meeting link can be found on Blackboard (see LIVE ZOOM MEETINGS
on the left navigation menu), and will start at 2:00 PM Monday (for section 1) or Tuesday (for section 2).
If you are unable to join this live session, or if you want to review, you can find the recording stored on Blackboard via Panopto (see Class Recordings
on the left navigation menu).
Today is introductory, but you may look at Chapter 1 if you wish, to remind you about the use of models in economics. Otherwise, please heed this timeless message:
A message to students from the Doggfather himself, @SnoopDogg pic.twitter.com/wsSANYv8u6
— Ryan Briggs (@ryancbriggs) August 12, 2020
Please note going forward, the lesson numbers and topics (e.g. 1.1) are my design, and will not match up with the textbook!
NONE
Please take the preliminary math survey on your math background by 11:59 PM Sunday February 7. This will help us all have a productive course together.


--- layout: post title: "Semigroups accumulate" description: "You can accumulate an arbitrary, non-zero number of semigroup values to a single value. An article for object-oriented programmers." date: 2017-12-11 8:28 UTC tags: [Software Design] --- {% include JB/setup %}
{{ page.description }}
This article is part of a series about semigroups. In short, a semigroup is an associative binary operation.
As you've learned in a previous article, you can accumulate an arbitrary number of monoidal values to a single value. A corresponding property holds for semigroups.
When an instance method Op
forms a monoid, you can easily write a function that accumulates an arbitrary number of Foo
values:
public static Foo Accumulate(IReadOnlyCollection<Foo> foos) { var acc = Identity; foreach (var f in foos) acc = acc.Op(f); return acc; }
Notice how this generally applicable algorithm starts with the Identity
value. One implication of this is that when foos
is empty, the return value will be Identity
. When Op
is a semigroup, however, there's no identity, so this doesn't quite work. You need a value to start the accumulation; something you can return if the collection is empty.
From Haskell you can learn that if you have a semigroup, you can accumulate any non-empty collection:
sconcat :: Semigroup a => NonEmpty a -> a
You can read this as: for any generic type a
, when a
forms a Semigroup
, the sconcat
function takes a non-empty list of a
values, and reduces them to a single a
value. NonEmpty a
is a list with at least one element.
You can also define a NotEmptyCollection<T>
class in C#:
public class NotEmptyCollection<T> : IReadOnlyCollection<T> { public NotEmptyCollection(T head, params T[] tail) { if (head == null) throw new ArgumentNullException(nameof(head)); this.Head = head; this.Tail = tail; } public T Head { get; } public IReadOnlyCollection<T> Tail { get; } public int Count { get => this.Tail.Count + 1; } public IEnumerator<T> GetEnumerator() { yield return this.Head; foreach (var item in this.Tail) yield return item; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }
Because of the way the constructor is defined, you must supply at least one element in order to create an instance. You can provide any number of extra elements via the tail
array, but one is minimum.
The Count
property returns the number of elements in Tail
, plus one, because there's always a Head
value.
The GetEnumerator
method returns an iterator that always starts with the Head
value, and proceeds with all the Tail
values, if there are any.
As you've already learned, Math.Max
is a semigroup. Although the .NET Base Class Library has built-in methods for this, you can use a generally applicable algorithm to find the maximum value in a non-empty list of integers.
private static int Accumulate(NotEmptyCollection<int> numbers) { var acc = numbers.Head; foreach (var n in numbers.Tail) acc = Math.Max(acc, n); return acc; }
Notice how similar this algorithm is to monoid accumulation! The only difference is that instead of using Identity
to get started, you can use Head
, and then loop over all elements of Tail
.
You can use it like this:
var nec = new NotEmptyCollection<int>(42, 1337, 123); var max = Accumulate(nec);
Here, max
is obviously 1337
.
As usual, however, this is much nicer, and more succinct in Haskell:
Prelude Data.Semigroup Data.List.NonEmpty> getMax $ sconcat $ fmap Max $ 42 :| [1337, 123] 1337
That's hardly the idiomatic way of getting a maximum element in Haskell, but it does show how you can 'click together' concepts in order to achieve a goal.
Perhaps the observant reader will, at this point, have recalled to him- or herself that the .NET Base Class Library already includes an Aggregate
extension method, with an overload that takes a seed. In general, the simpliest Aggregate
method doesn't gracefully handle empty collections, but using the overload that takes a seed is more robust. You can rewrite the above Accumulate
method using Aggregate
:
private static int Accumulate(NotEmptyCollection<int> numbers) { return numbers.Tail.Aggregate( numbers.Head, (x, y) => Math.Max(x, y)); }
Notice how you can pass Head
as the seed, and accumulate the Tail
using that starting point. The Aggregate
method is more like Haskell's sconcat
for semigroups than mconcat
for monoids.
A semigroup operation can be used to reduce values to a single value, just like a monoid can. The only difference is that a semigroup operation can't reduce an empty collection, whereas a monoid can.
Next: Quasigroups


This example show a group of controls that compose a Form. Notice that the form's controls (input text boxes and radio buttons) make use
of the ng-model directive that tells angular that these controls are tied to the model using an object called "user".
Important thing to notice:
1. Check that we have customized 2 of the CSS classes used by angular automatically. When the control in the form has been touched and it has failed validation (i.e. in case of input control, invalid will be an invalid email) then the style we
defined will paint the control in red color. This is the style that was implemente: .css-form input.ng-invalid.ng-touched
. Similarly, if the control has been touched and it is valid, this .css-form input.ng-valid.ng-touched will paint the control in green.
2. In angular, these classes are set automatically to our controls. We can modify the look and feel by just ensuring that our pages define the stlyes.
form = {{user | json}}
master = {{master | json}}


|
|
| Temp (int id, string name, int size, int offset) |
| |
|
virtual bool | equals (Temp *temp) |
| |
|
virtual string | toString (void) |
| |
|
|
static Temp * | createTempI4 (void) |
| |
|
static Temp * | createConstTemp (int value) |
| |
|
|
int | id |
| |
|
string | name |
| |
|
int | offset |
| |
|
int | size |
| |
|
Variable * | sym |
| |
|
int | value |
| | for const temp
|
| |
|
bool | isConst |
| | whether is constant or not
|
| |
|
bool | isParam |
| | whether is parameter of function or not, offset = (ebp+4, 8...)
|
| |
|
|
static int | tempCount |
| | for id
|
| |
|
static map< int, Temp * > * | constTempPool |
| |
Definition at line 87 of file Tac.h.
The documentation for this class was generated from the following file:


What's new School is starting again! This website is new and fresh, ready to be used! This site is highly customizable! Change your font, colour scheme, username, and more!


--- name: playground.actionsheet url: /actionsheet animationIn: slideFromLeft animationOut: fadeOut ---
Some html


Gilbey Street
[0, 50]
|
the Loveridge Arms
[1, 50]
|
the Wriford Museum
[2, 50]
|
Kitchingman Place
[3, 50]
|
Colmer Way
[4, 50]
|
Markess Bank
[5, 50]
|
St Seraphim's Hospital
[6, 50]
|
the Ripley Building
[7, 50]
|
the Burtoft Arms
[8, 50]
|
the Shiplow Building
[9, 50]
|
Haddock Road Police Dept
[0, 51]
|
Edmund General Hospital
[1, 51]
|
the Bengefield Hotel
[2, 51]
|
Wrentmore Bank
[3, 51]
|
Grey Bank
[4, 51]
|
Abney Boulevard
[5, 51]
|
Forshaw Drive
[6, 51]
|
a junkyard
[7, 51]
|
a carpark
[8, 51]
|
the Monks Arms
[9, 51]
|
Besant Avenue
[0, 52]
|
Sherring Place
[1, 52]
|
the Wakeford Motel
[2, 52]
|
Victor General Hospital
[3, 52]
|
the Linnett Museum
[4, 52]
|
Adam Plaza
[5, 52]
|
Dauncey Towers
[6, 52]
|
Lansdowne Crescent
[7, 52]
|
Shortman Lane
[8, 52]
|
McIlhargey Plaza
[9, 52]
|
Moodborn Library
[0, 53]
|
Gilles Street
[1, 53]
|
Paillet Alley
[2, 53]
|
McGarth Plaza
[3, 53]
|
Redfern Boulevard
[4, 53]
|
Pople Street
[5, 53]
|
Tozer Place
[6, 53]
|
Rayment Row
[7, 53]
|
St Julius's Hospital
[8, 53]
|
Cornelius General Hospital
[9, 53]
|
Low Walk
[0, 54]
|
Leighton Way
[1, 54]
|
Ackerman Walk
[2, 54]
|
Waugh Road
[3, 54]
|
Haygarth Row Railway Station
[4, 54]
|
Campain Drive
[5, 54]
|
Mack Auto Repair
[6, 54]
|
Whish Walk
[7, 54]
|
the Watherston Hotel
[8, 54]
|
a factory
[9, 54]
|
Club Whittem
[0, 55]
|
Kempe Auto Repair
[1, 55]
|
Ivins Towers
[2, 55]
|
the MacGilvray Hotel
[3, 55]
|
Brower Lane
[4, 55]
|
a carpark
[5, 55]
|
a carpark
[6, 55]
|
Bowers Boulevard School
[7, 55]
|
the Sankey Arms
[8, 55]
|
Murrey Square
[9, 55]
|
a warehouse
[0, 56]
|
the Timmins Building
[1, 56]
|
the Mees Monument
[2, 56]
|
the Ashwin Building
[3, 56]
|
Sullivan Walk
[4, 56]
|
the Heneage Monument
[5, 56]
|
the Lane Monument
[6, 56]
|
the Estmond Museum
[7, 56]
|
the Crawshaw Building
[8, 56]
|
Cleverly Lane
[9, 56]
|
Spry Road Police Dept
[0, 57]
|
Woof Plaza School
[1, 57]
|
Viney Place
[2, 57]
|
Lees Boulevard Police Dept
[3, 57]
|
a warehouse
[4, 57]
|
Veazey Plaza
[5, 57]
|
Greatwood Road
[6, 57]
|
a warehouse
[7, 57]
|
a factory
[8, 57]
|
Spooner Lane
[9, 57]
|
wasteland
[0, 58]
|
Higdon Crescent
[1, 58]
|
Falvey Boulevard
[2, 58]
|
Riddles Place
[3, 58]
|
Blaxall Way Police Dept
[4, 58]
|
a warehouse
[5, 58]
|
St Wolfgang's Hospital
[6, 58]
|
Pye Street
[7, 58]
|
the Whitcombe Hotel
[8, 58]
|
Club Allerston
[9, 58]
|
St Laurence's Church
[0, 59]
|
Wigfield Avenue
[1, 59]
|
Club Whittard
[2, 59]
|
Upsdale Bank
[3, 59]
|
the Merson Building
[4, 59]
|
the Langner Building
[5, 59]
|
the Maidment Building
[6, 59]
|
the Pincoffs Building
[7, 59]
|
Bastable Alley
[8, 59]
|
a carpark
[9, 59]
|
|
Menu
City Map
Find Location
Route Finder
World View
Map Mirror
|


Personal Creations
I've explored the kitchen and produced these recipes. And I didn't include my life story before each recipe.
- Sandwich bread
- Jalapeno cheese bread
- Pizza dough
- Bagels
- Banana bread
- Raspberry rolls - or cinnamon rolls
- Pancakes
- Scones
My Favorites
Primarily for me to not forget delicious memories.


{% extends "demo/base.html" %}
{% block content %}
{% include "demo/includes/intro.html" with intro=self.intro only %}
{% include "demo/includes/carousel.html" with carousel_items=self.carousel_items.all only %}
{% include "demo/includes/body.html" with body=self.body only %}
{% include "demo/includes/related_links.html" with related_links=self.related_links.all only %}
{% endblock %}


bsnav
Home
Megamenu
Megamenu grid
Shoes
Originals
Soccer
Rinning
Basketball
Training
Outdoor
Football
Baseball
Tennis
Sandals & Slides
NEO
Apparel
Jackets
Hoodies & Sweatshirts
Track Suits & Warm Ups
Long Sleeve Tops
Short Sleeve Tops
Graphic Tees
Sleeveless Tops
Jerseys
Pants
Tights
Shorts
Accessories
Bags
Balls
Sunglasses
Watches
Gloves
Hats
Socks
Underwear
Scarves
Sports
Soccer
Running
Basketball
Training
Football
Baseball
Tennis
Outdoor
Weightlifting
Skateboarding
Snowboarding
Lacrosse
Grid
Megamenu grid
col 3
col 3
col 3
col 3
col 4
col 4
col 4
col 6
col 6
News
Gallery
Contact
Mega Menu