I need to generate vector of maps filled with random data, that look something like this:
{
:amount 9999
:booking-date "2015-12-21"
:effective-date "2015-12-21"
:id "01244f01-1933-4a8d-8b92-07796e3e62f0"
:reconciled false
:transaction_id "000014543583"
}
I was thinking to use either clojure/data.generators or 'clojure.test.check/generators`,
being new to clojure struggling with that. Can you trow me a code snippet. Thanks
You can see an example for test.check in some unit tests for the Tupelo Library.
I would also recommend looking at all of the examples and links at the GH page for test.check: https://github.com/clojure/test.check
Related
Context
I have a function that operates on a data structure.
I have written a spec for the data structure this function operates on.
This function returns a reagent component that is rendered in a browser (PhantomJS)
The spec has some optional keys, and depending on whether or not those keys exist in the data when it's passed to the function, the output (component to be rendered in browser) of the aforementioned function will be affected.
I am looking to use clojure.test to compare values of the data structure passed to the function generating the component with values grabbed from the rendered element, so simple unit test or input->output comparison is not what I'm going for here.
Problem
Since calling generate or sample on the spec generator will sometimes include or omit the optional fields, I would like to iterate over a reasonably large set of data generated using sample and test each of the data structures, but I don't know the "right" or idiomatic way to do this.
I have used are in clojure.test before, which is great, but since I'm testing against the rendered component in the browser, and are tests input->output it doesn't seem like the right tool for the job.
Advice on a generally accepted practice here or language/clojure.test feature that would have me doing this in the most idiomatic way would be greatly appreciated.
compare values of the data structure passed to the function generating the component with values grabbed from the rendered element
If possible, I'd use s/fdef with :args, :ret, and :fn args to specify the relationship between your function's input and output, and then check the function. There's an example in the testing section of spec guide.
iterate over a reasonably large set of data generated using sample and test each of the data structures
This is essentially what check does.
As for clojure.test integration, you can check functions as part of a test suite like this:
(deftest foo-test
(is (not (:check-failed (st/summarize-results (st/check `foo))))))
Om.Next is an excellent and clean UI library for use with Clojure and Clojurescript and I'm trying to add functionality for commenting to our website.
Essentially: entities have a bid (blurb-id) and now I want to add comments.
My idea is:
entities get a :cid (comment-id) and also they have the attributes :root_bid and :parent_cid
So every comment looks like:
{:cid 676767
:root_bid 5252
:parent_cid 676765
:contents "this is a comment"
:author "this#email.com"
:total-score 70
:number-of-votes 1 }
And that's basically everything I need to be able to store a comment.
So far so good, but now I want to recursively render comments, Fred comments on Jane's blurb, Jesus comments on Fred's comment, Josephine comments on Jesus' comment...
How can I recursively map comments using this datastructure?
I'm stumped so I appreciate any help.
I'm writing a simple photo library app in Clojure. I have a library map that has the :photos key which is a vector of photo maps. Then, I have a function that adds a photo to a library---it takes the library object and the photo to be added as arguments.
(defn add-to-library [library photo]
...
)
It returns a library map with the photo added.
Now, I want to "map" this function over a list of photos. I need to be able to pass the library object through from one iteration to the next.
What is the idiomatic way of doing this in Clojure?
Try:
(reduce add-to-library library list-of-photos).
The reduce function is wonderful, and is a general tool that is surprisingly applicable in a lot of specific situations. Many of those situations are ones like yours, where you have a "collection of things", a "function that adds a thing to that collection", and a "list of things to add". Maybe this isn't starting material if first learning about reduce, but I found it very interesting: http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html
I've just started learning Clojure and I'm attempting to write something to pull some URL's from a web page into memory with some additional meta data around each URL.
I can get the URLs but it's storing them somewhere that I'm having an issue with. I've figured out I need a vector with nested maps, which I can then add new records to with assoc-in, however since I don't know the URL's I'm not sure how I go about defining my data structure initially.
So for example:
(def *comics*
[{:name "Penny-Arcade"
:url "http://www.penny-arcade.com/comic/"
:working 0
}
{:name "We The Robots"
:url "http://www.wetherobots.com/"
:working 0
}])
I'm just not sure how I start the above data structure with no data in it, then add it say initially from a command line arg, then the rest from the website.
If someone can suggest a better way that the above to store the data, please feel free.
I take it you want to modify your *comics* var from some command line argument - and then modify it even more while "working" on the elements in it.
I would suggest you don't do that.
There doesn't seem to be any reason you can't take the comics urls from the command line and pass them as arguments to a function that does the processing and returns whatever you want from those urls. Doing it that way - that is; functionally, without mutating vars - will definitely be easier to implement in clojure, easier to parallellize and just all out more idiomatic and fun.
I'd like to run a session about Clojure. Could you recommend a problem which can be elegantly solved using functional programming with Clojure? Can you point to resources which cover this topic?
A lot of arguments for using Clojure seem to be related to its handling of concurrency, but I will not touch that issue here.
I will list some problems that I am forced to deal week in, week out with Java and how I have or would solve them in Clojure.
Immutability
In Java achieving immutability is very very hard. Besides following strict coding practices you will have to choose your frameworks and libraries very carefully. Also as a side-effect you will either write a lot of code to make a clean and usable API, or just force the client to deal with it.
final Person person = personDao.getById(id);
// I would like to "change" the person's email, but no setters... :(
In Clojure you model your data based on immutable data structures so all of your objects are immutable by default and due to this Clojure offers powerful functions which operate on these structures.
(let [person (get-by-id person-dao id)
person-with-email (assoc person :email email)]
; Use person-with-email...
Conversions
In Java you have a domain class Person with fields id, name, email, socialSecurityNumber and others. You are creating a web service for retrieving the names and emails of all the persons in your database. You do not want to expose your domain so you create a class PersonDto containing name and email. That was easy, so now you need a function to map the data from Person to PersonDto. Probably something like this:
public class PersonPopulator {
public PersonDto toPersonDto(Person person) {
return new PersonDto(person.getName(), person.getEmail());
}
public List<PersonDto> toPersonDtos(List<Person> persons) {
List<PersonDto> personDtos = new ArrayList<PersonDto>();
for (Person person : persons) {
personDtos.add(toPersonDto(person));
}
return personDtos;
}
}
Okay well that wasn't so bad, but what if you want to put more data in the DTO? Well the constructor code in toPersonDto will grow a bit, no worries. What if there are two different use cases, one as above and another where we want to send just the emails? Well we could leave the name null (bad idea) or create a new DTO, perhaps PersonWithEmailDto. So we would create a new class, a few new methods for populating the data... you probably see where this is going?
Clojure, a dynamically typed language with immutable data structures, allows me to do this:
(defn person-with-fields [person & fields]
(reduce #(assoc %1 %2 (get person %2)) {} fields))
(person-with-fields {:id 1
:name "John Doe"
:email "john.doe#gmail.com"
:ssn "1234567890"} :name :email)
; -> {:email "john.doe#gmail.com", :name "John Doe"}
And to manipulate a list of persons:
(map #(person-with-fields % :name :email) persons)
Also adding ad hoc data to a person would be easy:
(assoc person :tweets tweets)
And this would break nothing. In Java if your objects are immutable they probably don't have setters, so you would have to write a lot of boilerplate just to modify one field (new Person(oldPerson.getName(), oldPerson.getEmail(), tweets)), or create a totally new class. Mutable objects offer a nice API (oldPerson.setTweets(tweets)), but are difficult to test and understand.
Testing
A lot of Java code is based on some state even when there is no need for it. This means you can either mock this state, which usually means additional boilerplate and gets harder if you have not created your code with testability in mind. On the other hand tests without mocks are usually slow and depend on database access or time or something else that will surely fail on you from time to time.
While coding Clojure I have noticed that I do not actually need state that much. Pretty much the only situations are when I am retrieving something from the "outside", be it a database or some web service.
Summary
My code is a pipe, from one end I get some data, this data is then changed in the pipe via filtering, transforming or joining it with some other data until it reaches the end of the pipe. Inside the pipe there is no need to really change the data, but a lot of cases where powerful functions and immutable data structures are useful and this is why Clojure works wonders with code like this.
The classic concurrency problem "The Sleeping Barber" might be good.
Here is a couple of examples
http://www.bestinclass.dk/index.clj/2009/09/scala-vs-clojure-round-2-concurrency.html
https://github.com/bitsai/clojure-actors/blob/master/sleeping_barber.clj
A couple of months ago I run into the same problem and we decided to solve 'the Mona Lisa' problem in Clojure. The result was this presentation. Basically we showed that Clojure is extremely cool for solving problems for which 'code as data' gives an elegant solution. For example in genetic algorithms.