Function that accepts two lists of predicates and elements list and partitions the elements list accordingly - lisp

i want to write a function that accepts two lists of predicates functions and elements list and returns all the members in the original list that hold all the predicates in pre1_list and delete the members in the original list that unhold all the predicates in pre2_list
i am writing this code in a language called mini lisp , it's similar to lisp but more simple ,but that doesn't matter , i just want help on how to do such a thing ? an idea of how to implement such code !
how i am thinking to do it : (just the beginning of my idea)
(defun get_pred_1_not_2 (pre1_list pre2_list list)
(cond
((null list) NIL)
; return all the members in the original list that hold all the predicates in pre1_list
(pre1_list (get_pred_1_not_2 (cdr pre1_list) pre2_list (filter_pre list (car pre1_list))))
; delete all the members in the original list that unhold all the predicates in pre2_list
(pre2_list (get_pred_1_not_2 pre1_list (cdr pre2_list) ;.... (
where filter_pre is a function that returns all the element from the list that holds predications giving to it
i hope someone could help ! as this function is really deficult to write and i don't want to just give up
thank you

Don't try building the whole solution all at once. Instead proceed by building the building blocks for yourself, function by function, for simple enough tasks so that each function is easy to write. That's the "functional programming" approach.
Start with the simple filter function for one predicate. Then modify it to have your filter-not.
Then use them to implement filter-ps and filter-not-ps.
Alternatively, turn your list of predicates into one predicate by writing all-ps and all-ps-not functions.
The produced predicate will work with one element at a time, so you can use it with the simple filter to get what you want, with two calls to filter -- first with the result of all-ps applied to your first predicates list; second with the result of all-ps-not applied to your second predicates list.
edit: if you delete all elements for which all predicates "unhold" i.e. return false, you are left with all the elements for which at least one of the predicates returns true. So you might as well say, for the second part of the task, that you want to keep all elements for which at least one of the predicates hold. Still the same general guidelines apply, just that instead of defining all-ps-not you need to define at-least-one-of-ps, or perhaps name it some-ps.

Related

Lisp Function Interpretation

I am reading a book and I am confused on what the following code does:
(defmethod execute ((o ORDER) (l SIMUL) (e MARKETUPDATE))
(values
(list (make-TRADE :timestamp (timestamp e)
:price (price e)
:quantity (orderquantity o)))
NIL))
The source to which I got this function says that it returns two values. My question is what the body does. From my understanding, the line 3-5 creates a list with :timestamp, :price, :quantity. Am I correct? What about values, the second line? Does it return this variable too? Any summary would help. Thanks
This is a method for a generic function, specializing on arguments of types order, simul, and marketupdate.
It returns 2 values:
A list of length 1 created by the eponymous function list, which contains a single object of, presumably, type trade (probably - but not necessarily - created by a defstruct), which has slots timestamp, price, and quantity.
Symbol nil.
You can probably access the slots of the trade using functions trade-timestamp &c (unless the defstruct form is non-trivial or trade is not defined by a defstruct at all).
Why the result of make-trade is wrapped in a list is hard to guess without more context, but I'd guess that an execute can be split into N trades in some scenarios.
I suspect your confusion arises almost entire because this is the first time you have encountered a use of values. Common Lisp allows functions to return multiple values. That's slightly similar to how any language allows functions to receive multiple parameters.
These multiple return values are quite efficiently implemented. Most newbies encounter multiple values for the first time on the integer division functions, which will return a remainder as their second value. Hash table look ups will return a second value to indicate if the key was actually in the table, since the value stored for the key might be nil.
In your example the second value is NIL, presumably other execute methods might return something more interesting - for example where in the update Q the order was place, or an error code if something goes wrong. Of course checking out the manual for values will be fraught with educational values(sic).
This function is a method returning two values by using the keyword values. Have a look at CLOS to better understand object orientation and at "values" for the way of returning more than one value.

How to check if the value is a number in Prolog manually?

How to check if the given value is a number in Prolog without using built-in predicates like number?
Let's say I have a list [a, 1, 2, 3]. I need a way to check if every element within this list is a number. The only part of the problem that bothers me is how to do the check itself without using the number predicate.
The reason why I'm trying to figure this out is that I've got a college assignment where it's specifically said not to use any of the built-in predicates.
You need some built-in predicate to solve this problem - unless you enumerate all numbers explicitly (which is not practical since there are infinitely many of them).
1
The most straight-forward would be:
maplist(number, L).
Or, recursively
allnumbers([]).
allnumbers([N|Ns]) :-
number(N),
allnumbers(Ns).
2
In a comment you say that "the value is given as an atom". That could mean that you get either [a, '1', '2'] or '[a, 1, 2]`. I assume the first. Here again, you need a built-in predicate to analyze the name. Relying on ISO-Prolog's errors we write:
numberatom(Atom) :-
atom_chars(Atom, Chs),
catch(number_chars(_, Chs), error(syntax_error(_),_), false).
Use numberatom/1 in place of number/1, So write a recurse rule or use maplist/2
3
You might want to write a grammar instead of the catch... goal. There have been many such definitions recently, you may look at this question.
4
If the entire "value" is given as an atom, you will need again atom_chars/2or you might want some implementation specific solution like atom_to_term/3 and then apply one of the solutions above.

comparing an element with all elements in a list

I'm learning Scala now, and I have a scenario where I have to compare an element (say num) with all the elements in a list.
Assume,
val MyList = List(1, 2, 3, 4)
If num is equal to anyone the elements in the list, I need to return true. I know to do it recursively using the head and tail functions, but is there a simpler way to it (I think I'll be able to do it using foreach, but I'm not sure how to implement it exactly)?
There is number of possibilities:
val x = 3
MyList.contains(x)
!MyList.forall(y => y != x) // early exit, basically the same as .contains
If you plan to do it frequently, you may consider to convert your list to Set, cause every .contains lookup on list in worst case is proportional to number of elements, whereas on Set it is effectively constant
val mySet = MyList.toSet
mySet.contains(x)
or simply:
mySet(x)
A contains method is pretty standard for lists in any language. Scala's List has it too:
http://www.scala-lang.org/api/current/scala/collection/immutable/List.html
As others have answered, the contains method on the list will do exactly this, and it's the most understandable/performant way.
Looking at your closing comments though, you wouldn't be able to do it (in an elegant fashion) with foreach, since that returns Unit. Foreach "does" something for each element, but you don't get any result back. It's useful for logging/println statements, but it doesn't act as a transformation.
If you want to run a function on every element individually, you would use map, which returns a List of the results of applying the function. So assuming num = 3, then MyList.map(_ == num) would return List(false, false, true, false). Since you're looking for a single result, and not a list of results, then this is not what you're after.
In order to collapse a sequence of things into a single result, you would use a fold over the data. Folding involves a function that takes two arguments (the result so far, and the current thing in the list) and returns the new running result. So that this can work on the very first element, you also need to provide the initial value to use for the ongoing result (usually some sort of zero).
In your particular case, then, you want a Boolean answer at the end - "was an element found that was equal to num". So the running result would be "have I seen an element so far that was equal to num". Which means the initial value is false. And the function itself should return true if an element has already been seen, or if the current element is equal to num.
Putting this together, it would look like this:
MyList.foldLeft(false) { case (runningResult, listElem) =>
// return true if runningResult is true, or if listElem is the target number
runningResult || listElem == num
}
This doesn't have the nice aspect of stopping as soon as the target value has been found - and it's nowhere near as concise as calling MyList.contains. But as an instructional example, this is how you could implement this yourself from the primitive functional operations on a list.
List has a method for that:
val found = MyList.contains(num)

How to delete elements from a transformed collection using a predicate?

If I have an ArrayList<Double> dblList and a Predicate<Double> IS_EVEN I am able to remove all even elements from dblList using:
Collections2.filter(dblList, IS_EVEN).clear()
if dblList however is a result of a transformation like
dblList = Lists.transform(intList, TO_DOUBLE)
this does not work any more as the transformed list is immutable :-)
Any solution?
Lists.transform() accepts a List and helpfully returns a result that is RandomAccess list. Iterables.transform() only accepts an Iterable, and the result is not RandomAccess. Finally, Iterables.removeIf (and as far as I see, this is the only one in Iterables) has an optimization in case that the given argument is RandomAccess, the point of which is to make the algorithm linear instead of quadratic, e.g. think what would happen if you had a big ArrayList (and not an ArrayDeque - that should be more popular) and kept removing elements from its start till its empty.
But the optimization depends not on iterator remove(), but on List.set(), which is cannot be possibly supported in a transformed list. If this were to be fixed, we would need another marker interface, to denote that "the optional set() actually works".
So the options you have are:
Call Iterables.removeIf() version, and run a quadratic algorithm (it won't matter if your list is small or you remove few elements)
Copy the List into another List that supports all optional operations, then call Iterables.removeIf().
The following approach should work, though I haven't tried it yet.
Collection<Double> dblCollection =
Collections.checkedCollection(dblList, Double.class);
Collections2.filter(dblCollection, IS_EVEN).clear();
The checkCollection() method generates a view of the list that doesn't implement List. [It would be cleaner, but more verbose, to create a ForwardingCollection instead.] Then Collections2.filter() won't call the unsupported set() method.
The library code could be made more robust. Iterables.removeIf() could generate a composed Predicate, as Michael D suggested, when passed a transformed list. However, we previously decided not to complicate the code by adding special-case logic of that sort.
Maybe:
Collection<Double> odds = Collections2.filter(dblList, Predicates.not(IS_EVEN));
or
dblList = Lists.newArrayList(Lists.transform(intList, TO_DOUBLE));
Collections2.filter(dblList, IS_EVEN).clear();
As long as you have no need for the intermediate collection, then you can just use Predicates.compose() to create a predicate that first transforms the item, then evaluates a predicate on the transformed item.
For example, suppose I have a List<Double> from which I want to remove all items where the Integer part is even. I already have a Function<Double,Integer> that gives me the Integer part, and a Predicate<Integer> that tells me if it is even.
I can use these to get a new predicate, INTEGER_PART_IS_EVEN
Predicate<Double> INTEGER_PART_IS_EVEN = Predicates.compose(IS_EVEN, DOUBLE_TO_INTEGER);
Collections2.filter(dblList, INTEGER_PART_IS_EVEN).clear();
After some tries, I think I've found it :)
final ArrayList<Integer> ints = Lists.newArrayList(1, 2, 3, 4, 5);
Iterables.removeIf(Iterables.transform(ints, intoDouble()), even());
System.out.println(ints);
[1,3,5]
I don't have a solution, instead I found some kind of a problem with Iterables.removeIf() in combination with Lists.TransformingRandomAccessList.
The transformed list implements RandomAccess, thus Iterables.removeIf() delegates to Iterables.removeIfFromRandomAccessList() which depends on an unsupported List.set() operation.
Calling Iterators.removeIf() however would be successful, as the remove() operation IS supported by Lists.TransformingRandomAccessList.
see: Iterables: 147
Conclusion: instanceof RandomAccess does not guarantee List.set().
Addition:
In special situations calling removeIfFromRandomAccessList() even works:
if and only if the elements to erase form a compact group at the tail of the List or all elements are covered by the Predicate.

Questions about Lists and other stuff in Clojure

I have a few questions concerning Lists, classes and variables in clojure.
This may seem quite stupid but how do I access elements in a List ?
I'm coding a program that allows you to manipulate a phonebook; You can add an entry, delete one or print the information about one. This leads me to two questions :
Is there a way to create a class "entry" that would contain "name" "adress" "phone number" variables ? or is that impossible in clojure (and functional programming in general ?) If I can't have a List of objects containing that information, how would I go about this task ?
I was thinking of having a function that reads user input to know what the user wants to do (add entry, delete entry or print info) then calls the appropriate function to do that which calls back the first function when it's done. Is passing as a parameter the List of entries to each function the right thing to do ?
This may seem quite stupid but how do I access elements in a List ?
(nth coll index)
For example:
(nth [1 2 3 4] 2) ; -> 3 (since it uses zero-based indexing)
Is there a way to create a class "entry" that would contain "name" "adress" "phone number" variables ? or is that impossible in clojure (and functional programming in general ?) If I can't have a List of objects containing that information, how would I go about this task ?
It's possible in Clojure, but unidiomatic. In Clojure, the basic abstraction for data entities are maps, not classes (except for some corner cases where direct interoperation with Java frameworks is needed). So you would just use a map:
(def entry {:name "x" :address "y" :phone-number "z"})
To access the item's name, you either use
(:name entry)
or
(get entry :name)
The former works only when the keys of the map are keywords, the latter works with all types of key.
So for your example, your data model (the phonebook) would be a seq (say, a list or a vector) of such maps.
I was thinking of having a function that reads user input to know what the user wants to do (add entry, delete entry or print info) then calls the appropriate function to do that which calls back the first function when it's done. Is passing as a parameter the List of entries to each function the right thing to do?
Since your model consists of only one main data structure (the phone book seq), passing it as an arg is certainly an appropriate way to design your functions. If you expect to have more kinds of top-level containers (i.e. for a more real world application), I'd recommend looking into the Application Context Pattern, which will look a bit intimidating at first (at least it did for me, and it contains a lot of Clojure-specific jargon), but is well worth the effort to learn.
Have you considered buying the book Programming Clojure? A pdf version is only $21 US. Well worth the money in my opinion.
(entry :name)
will also work as well when accessing a map. So you have three ways of accessing an element of a map by using the keyword:
(entry :name)
or
(:name entry)
or
(get entry :name)
where
(def entry {:name "x" :address "y" :phone-number "z"})
As Rayne mentioned, the second form is only possible if the key is a keyword. You can use the other "short" form with keys of other types:
user=>(def my-map {"a" "b" "c" "d"})
user=>(my-map "c")
"d"
user=>(get my-map "a")
"b"
For part one of your question, if you will be accessing the items in your list with (nth ...) you may consider using a vector. Vectors are not like arrays in other languages. for instance chopping them and adding new elements to the end are also efficient in addition to numerical indexing. Under the hood the arrays are actually very similar to maps.
best of all arrays are functions of an index:
(def a [1 2 3 4])
(a 2) ==> 3
for parts 2 and 3 pmf's answer cover them very nicely.