Skip to content

Commit

Permalink
Add helper function for adding or replacing elements to a list
Browse files Browse the repository at this point in the history
  • Loading branch information
Dylan Harries committed Dec 16, 2016
1 parent 8719c4d commit 18eb92a
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions meta/Utils.m
@@ -1,6 +1,9 @@

BeginPackage["Utils`"];

AppendOrReplaceInList::usage="Replaces existing element in list,
or appends it if not already present.";

ApplyAndConcatenate::usage = "Applies a function to a list and
concatenates the resulting list.";

Expand Down Expand Up @@ -88,6 +91,17 @@ occurrence of the given rule is replaced (if it exists) or added (if

Begin["`Private`"];

AppendOrReplaceInList[values_List, elem_, test_:SameQ] :=
Module[{matches, result},
matches = test[elem, #]& /@ values;
matches = (If[# =!= True && # =!= False, False, #])& /@ matches;
If[!Or @@ matches,
result = Append[values, elem];,
result = ReplacePart[values, Position[matches, True] -> elem];
];
result
];

ApplyAndConcatenate[Func_, l_List] :=
Module[{result = ""},
(result = result <> Evaluate[Func[#]])& /@ l;
Expand Down

0 comments on commit 18eb92a

Please sign in to comment.