Questions about Lists and other stuff in Clojure - class

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.

Related

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

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.

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.

PLT Redex: parameterizing a language definition

This is a problem that's been nagging at me for some time, and I wonder if anyone here can help.
I have a PLT Redex model of a language called lambdaLVar that is more or less a garden-variety untyped lambda calculus, but extended with a store containing "lattice variables", or LVars. An LVar is a variable whose value can only increase over time, where the meaning of "increase" is given by a partially ordered set (aka a lattice) that the user of the language specifies. Therefore lambdaLVar is really a family of languages -- instantiate it with one lattice and you get one language; with a different lattice, and you get another. You can take a look at the code here; the important stuff is in lambdaLVar.rkt.
In the on-paper definition of lambdaLVar, the language definition is parameterized by that user-specified lattice. For a long time, I've wanted to do the same kind of parameterization in the Redex model, but so far, I haven't been able to figure out how. Part of the trouble is that the grammar of the language depends on how the user instantiates the lattice: elements of the lattice become terminals in the grammar. I don't know how to express a grammar in Redex that is abstract over the lattice.
In the meantime, I tried to make lambdaLVar.rkt as modular as I could. The language defined in that file is specialized to a particular lattice: natural numbers with max as the least-upper-bound (lub) operation. (Or, equivalently, natural numbers ordered by <=. It's a very boring lattice.) The only parts of the code that are specific to that lattice are the line (define lub-op max) near the top, and natural appearing in the grammar. (There's a lub metafunction that is defined in terms of the user-specified lub-op function. The latter is just a Racket function, so lub has to escape out to Racket to call lub-op.)
Barring the ability to actually specify lambdaLVar in a way that is abstract over the choice of lattice, it seems like I ought to be able to write a version of lambdaLVar with the most bare-bones of lattices -- just Bot and Top elements, where Bot <= Top -- and then use define-extended-language to add more stuff. For instance, I could define a language called lambdaLVar-nats that is specialized to the naturals lattice I described:
;; Grammar for elements of a lattice of natural numbers.
(define-extended-language lambdaLVar-nats
lambdaLVar
(StoreVal .... ;; Extend the original language
natural))
;; All we have to specify is the lub operation; leq is implicitly <=
(define-metafunction/extension lub lambdaLVar-nats
lub-nats : d d -> d
[(lub-nats d_1 d_2) ,(max (term d_1) (term d_2))])
Then, to replace the two reduction relations slow-rr and fast-rr that I had for lambdaLVar, I could define a couple of wrappers:
(define nats-slow-rr
(extend-reduction-relation slow-rr
lambdaLVar-nats))
(define nats-fast-rr
(extend-reduction-relation fast-rr
lambdaLVar-nats))
My understanding from the documentation on extend-reduction-relation is that it should reinterpret the rules in slow-rr and fast-rr, but using lambdaLVar-nats. Putting all this together, I tried running the test suite that I had with one of the new, extended reduction relations:
> (program-test-suite nats-slow-rr)
The first thing I get is a contract violation complaint: small-step-base: input (((l 3)) new) at position 1 does not match its contract. The contract line of small-step-base is just #:contract (small-step-base Config Config), where Config is a grammar nonterminal that has a new meaning if reinterpreted under lambdaLVar-nats than it did under lambdaLVar, because of the specific lattice stuff. As an experiment, I got rid of the contracts onsmall-step-base and small-step-slow.
I was then able to actually run my 19 test programs, but 10 of them fail. Perhaps unsurprisingly, all the ones that fail are programs that use natural-number-valued LVars in some way. (The rest are "pure" programs that don't interact with the store of LVars at all.) So, the tests that fail are exactly the ones that use the extended grammar.
So I kept following the rabbit hole, and it seems like Redex wants me to extend all of the existing judgment forms and metafunctions to be associated with lambdaLVar-nats rather than lambdaLVar. That makes sense, and it seems to work OK for judgment forms as far as I can tell, but with metafunctions I get into trouble: I want the new metafunction to overload the old one of the same name (because existing judgment forms are using it) and there doesn't seem to be a way to do that. If I have to rename the metafunctions, it defeats the purpose, because I'll have to write whole new judgment forms anyway. I suppose that what I want is a sort of late binding of metafunction calls!
My question in a nutshell: Is there any way in Redex to parameterize the definition of a language in the way I want, or to extend the definition of a language in a way that will do what I want? Will I end up just having to write Redex-generating macros?
Thanks for reading!
I asked the Racket users mailing list; the thread begins here. To summarize the resulting discussion: In Redex as it stands today, the answer is no, there is no way to parameterize a language definition in the way I want. However, it should be possible in a future version of Redex with a module system, which is in the works right now.
It also doesn't work to try to use Redex's existing extension forms (define-extended-language, extend-reduction-relation, and so on) in the way I tried to do here, because -- as I discovered -- the original metafunctions do not get transitively reinterpreted to use the extended languages. But a module system would apparently help with this, too, because it would allow you to package up metafunctions, judgment-forms, and reduction relations together and simultaneously extend them (see the discussion here).
So, for now, the answer is, indeed, to write a Redex-generating macro. Something like this works:
(define-syntax-rule (define-lambdaLVar-language name lub-op lattice-values ...)
(begin
;; Entire original Redex model goes here, with `natural` replaced with
;; `lattice-values ...`, and instances of `...` replaced with `(... ...)`
))
And then you can instantiate particular lattices with, e.g.,:
(define-lambdaLVar-language lambdaLVar-nat max natural)
I hope Redex does get modules soon, but in the meantime, this seems to work well.

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.

Recommended macros to add functionality to Clojure's defrecord constructor?

defrecord in clojure allows for defining simple data containers with custom fields.
e.g.
user=> (defrecord Book [author title ISBN])
user.Book
The minimal constructor that results takes only positional arguments with no additional functionality such as defaulting of fields, field validation etc.
user=> (Book. "J.R.R Tolkien" "The Lord of the Rings" 9780618517657)
#:user.Book{:author "J.R.R Tolkien", :title "The Lord of the Rings", :ISBN 9780618517657}
It is always possible to write functions wrapping the default constructor to get more complex construction semantics - using keyword arguments, supplying defaults and so on.
This seems like the ideal scenario for a macro to provide expanded semantics. What macros have people written and/or recommend for richer defrecord construction?
Examples of support for full and partial record constructor functions and support for eval-able print and pprint forms:
http://david-mcneil.com/post/765563763/enhanced-clojure-records
http://github.com/david-mcneil/defrecord2
David is a colleague of mine and we are using this defrecord2 extensively in our project. I think something like this should really be part of Clojure core (details might vary considerably of course).
The things we've found to be important are:
Ability to construct a record with named (possibly partial) parameters: (new-foo {:a 1})
Ability to construct a record by copying an existing record and making modifications: (new-foo old-foo {:a 10})
Field validation - if you pass a field outside the declared record fields, throw an error. Of course, this is actually legal and potentially useful, so there are ways to make it optional. Since it would be rare in our usage, it's far more likely to be an error.
Default values - these would be very useful but we haven't implemented it. Chas Emerick has written about adding support for default values here: http://cemerick.com/2010/08/02/defrecord-slot-defaults/
Print and pprint support - we find it very useful to have records print and pprint in a form that is eval-able back to the original record. For example, this allows you to run a test, swipe the actual output, verify it, and use it as the expected output. Or to swipe output from a debug trace and get a real eval-able form.
Here is one that defines a record with default values and invariants. It creates a ctor that can take keyword args to set the values of the fields.
(defconstrainedrecord Foo [a 1 b 2]
[(every? number? [a b])])
(new-Foo)
;=> #user.Foo{:a 1, :b 2}
(new-Foo :a 42)
; #user.Foo{:a 42, :b 2}
And like I said... invariants:
(new-Foo :a "bad")
; AssertionError
But they only make sense in the context of Trammel.
Here is one approach: http://david-mcneil.com/post/765563763/enhanced-clojure-records