(defn csv-data->maps [[head & lines]]
(map #(zipmap head %) lines))Any Clojure developer would understand what this does (its actually pretty straight forward), but to an outsider, it definitely looks strange.
Part of using Clojure is becoming familiar with the language, its syntax, and its idioms.
Rich even has a section in "Simple made easy" where he talks about this very thing; its on us to become familiar with the tools we are using.
I would highly recommend learning the spirit of Clojure first:
https://changelog.com/posts/rich-hickeys-greatest-hits
https://www.youtube.com/watch?v=vK1DazRK_a0
There are a few classes of tech that are uniquely Clojure:
Data driven DSLs:
- https://github.com/noprompt/garden
- https://github.com/weavejester/hiccup
- https://github.com/seancorfield/honeysql
Hyper normalised relational databases:
- https://github.com/replikativ/datahike
Advanced SPA tech (hyper normalised data driven):
- http://fulcro.fulcrologic.com/
- https://wilkerlucio.github.io/pathom/v2
Once you understand the spirit and rationale for Clojure it becomes apparent why other communities don't have this kind of tech yetOnce it gets down to practical things I recommend using clj-Kondo with type hints, Cursive for Intellji, make sure you learn how to hot code inject new code into your running program using your editor shortcuts, and TDD in Clojure is also excellent and immediate: https://cursive-ide.com/userguide/testing.html
Also look out for GraalVM and Babashka we're using it to compile fast native binaries out of Clojure
I'd suggest starting with what everyone seems to start with:
- https://www.braveclojure.com/clojure-for-the-brave-and-true/
Its a pretty fun read, and does a good job of covering the language (plus its free, which is probably why most people start there).
You could also take a look at Programming Clojure (written by some of the people behind the language, Alex Miller and Stuart Halloway), which I think is a better resource, but it does cost money.
It can be tempting to want to start in the deep end and try to create something like a web app from scratch as your first attempt at using the language, but there isn't really a Django or Rails for Clojure and you can easily get lost in the weeds (as I did).
My approach to learning Clojure was to start with a simple setup (for me its VS Code with the Calva extension, and deps.edn for managing the project files) and forcing myself to use Clojure for any small utility scripts that I might have otherwise done in bash or JavaScript.
This allowed me to get a feel for the language and how to work with the REPL without having to also digest a lot of information on how a specific library or framework works.
(defun csv-to-maps (csv)
(loop for row in (rest csv) collecting
(alist-hash-table
(mapcar #'cons (first csv) row) :test #'equal)))
For CSVs with only a few columns (maybe less than 10?), I'd probably go with alists instead of a hash table to save memory, and it'd look like this, using curry from Alexandria: (defun csv-to-alists (csv)
(map 'list (curry #'mapcar #'cons (first csv)) (rest csv)))> maps were built behind several abstractions. Thus, maps can start with a representation optimized for small maps and switch to a representation optimized for large collections if and when they ‘grow’ beyond a certain size.
Which is pretty cool, because basically the Clojure version of your code abstracts over alist-hash-table and alist, and the most optimal type of concrete map will automatically be created based on the size of the map you are asking to create.
Technically, since the hash-table implementation isn't specified in the CL standard an implementation could use a HAMT for the built-in hash tables, but I don't think any do.
So what I mean is Clojure will use an array backed map when you ask it to construct a small map, and it will give you a HAMT backed map when the map is large.
This is true as well as you add elements to a map, Clojure might automatically promote the map from an array map to a HAMT as its size grows.
No, not for a long time. The idiomatic C# way would be to use LINQ which actually predates Clojure a tiny bit. Java (since version 8 in 2014) could use Streams to similar effects. Either way the solution would be as short as your example.
My point was more that C#/Java developers (myself included at one point in time) would typically reach for classes to store the results, rather than just a Dictionary<String, String>.
It’s not that other languages can’t to this, it just that this approach doesn’t always jive with their conventions like it does with Clojure.
- define the class
- let the framework fully handle serializing/deserializing it from your file to the neat in-memory object
Everything comes in as a map, gets manipulated with the powerful set of core Clojure core functions, and spit back out as a different shaped map.
It’s a very flexible approach to dealing with data, and that is one of the main appeals of Clojure.
I wouldn’t suggest Java either, though. Go would be a better fit for that situation these days.
I look at Clojure and Go as different sides of a coin.
One is a powerful language the let’s a small team of experienced developers get a lot done with a small amount of code.
The other is a simple language that lets a lot of less experienced developers get a lot done with a lot of code.
I want to stress in this comparison though, that I don’t view one as better than the other.
Go was designed for development at scale, where you have lots of developers, all at different levels, all needing to contribute large amounts of code. In this respect, it does a great job at removing most of the rope that people can use to hang themselves. If I needed to pick one language to use at a large enterprise, it would probably be Go.
Clojure gives you a (different) set of limited functionality, but what it gives you is very powerful, and very foreign to most developers, so you can definitely hang yourself trying to force everyone into using it. If I got to choose one language for myself to use, it would be Clojure.
For people coming from a java background, I've had good results with other java+syntactic sugar languages as well, like Groovy and Kotlin, that have accelerated the growth of java to try to pick up some of the best parts of other more modern languages.
I would tend to disagree with the idea of "only choose one language for myself". You want to pick the right language for the job, you want to consider the business needs at hand, you want to consider the team that you have, you want to consider the experience that your team has. Even a company that would prefer to use as few languages as possible could easily end up with javascript for the frontend, ruby for the backend, go for infrastructure, python for ML. And at the end of the day, it's just code, it's just a tool to express your own skills as an engineer.
And then as an engineer personally, you need to get exposed to a range of languages, because each language teaches you a different mindset, and brings with it a different community with different priorities. Not referring to you specifically, but I've seen a lot of junior developers get into Clojure and all of a sudden it's the most amazing language because their life as a Java engineer before was horrible. But it's not Clojure specifically, it's the idea of learning new languages that is itself powerful.
So in practice, even at a large company, you find yourself with lots of small teams.
And no such small team at a large company would be composed exclusively of junior developers. There's at minimum going to be a team lead of some sort, and most often you'll have a spectrum from senior to junior.
So in reality, Clojure can be quite a good fit even at large companies. In fact, it might be a better fit at bigger companies, because I think small startup might actually be where you could find a small team of only juniors, and a "deliver at all cost no matter the quality" business need (due to not being profitable yet).
But then everyone that you on-board to that project has to be up to speed with how the code is being written and why.
With Clojure, that understanding is table-stakes.
So in that respect, the conclusion does write itself.
reads quite like Clojure, but looks foreign to JavaScript programmers...
I even made extensions to Ramda, so you can thread a mixture of async and non-async code with it: https://github.com/enumatech/sprites/blob/master/lib/fp.js#L...
At the end the friction was just annoying and no one else really understood the greatness of this approach, since they didn't know Clojure...
That said, this is where a lot of people who took a detour through Clojure, come out of it saying when they went back to their prior language or some other language, they felt like they had suddenly become better programmers, and it helped them even in other languages to write better programs. Clojure showed them the way, and now they can recognize it and think of doing it as such in other languages as well.
Maybe a different way to think of it is that you can do OOP in Clojure if you really want, but you won't. Similarly, in Java, you could try and do FP with immutable collections and value semantics, but most likely you're not going too.
And I'm using Java here because in theory, Java and Clojure have the exact same set of available features, they run on the same JVM, same runtime, compile to the same bytecode, can share libraries, etc. So it goes to show that the language itself does influence the style that is most convenient for writing your programs in.
The motivation to eventually use a Class would be to make use of static typing, e.g. when using an ORM like Entity Framework (a common usecase: reading a CSV file into a relational database). Static typing is usually considered a strength these days, but it does have its downsides (that debate has been done to death). Showing the parallel Clojure code for that could be very interesting.
However, reading CSVs doesn't require enforcing types, even if one wishes to use a library to deal with the complex quoting cases. CsvHelper is tilted in that direction of mapping to a static type, but it's not the only Csv reading library (I'm a pretty happy user of ExcelDataReader[0] for other reasons, and it doesn't enforce mapping. I'm sure there are more functional-style solutions out there). The original post picked the one place C# uses a powerful functional-like syntax, its generalized query language....
* From my limited understanding, not being a user of Clojure yet (I've been considering learning it for some time, just need to find time to do it seriously), each 'sequence' in the original example is a column, not a row. Were each sequence a row, in C# we could have used the positional lambda argument to get the columns.
var csv = ImmutableList<ImmutableList<string>>.Empty;
var map = csv.ToImmutableDictionary(y => y.First(), y => y.Skip(1).ToImmutableList());
I would hope they would then tell me that this will throw an exception when there is a repeat header in the csv data. I'm not sure the functional and safe version is that much cleaner than a for loop: var map = csv
.Where(x => !string.IsNullOrWhiteSpace(x.FirstOrDefault()))
.GroupBy(x => x.First())
.ToImmutableDictionary(x => x.Key, x => x.First().Skip(1).ToImmutableList());
Edit: But I would hire a developer that knew how to do the equivalent in Clojure without hesitation. let csvData = [
["Name", "Age", "Email"],
["John", 25, "[email protected]"],
["Mary", 30, "[email protected]"],
["Anne", 40, "[email protected]"],
]
let parseCSV = ([cols, ...rows]) =>
rows.map(row =>
row.reduce((res, val, i) => Object.assign(res, { [cols[i]]: val }), {}))
parseCSV(csvData)In my experience though, for every one elegant solution like yours, there will be ten developers writing nested for loops.
My example was never meant to be “look at what Clojure can do! You should all be jealous! “. Only an example of how Clojure encourages a different approach to solving problems that we are all familiar with.
You could simply implement the exact same functions in other languages too and end up with similar code, butsince its not built in, most people won’t think in those abstractions.
Ain't that the forever truth =/
nested for loops go brrrrrr
I think you would need something like this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
but I found it quite mind-bending when I tried it once. Clojure's way of building something like this out of a `lazy-seq` call feels simpler to me...
I, too, find the Clojure version to be easier to read, but I spend more time with Clojure than JS.
csv_to_maps([Head | Lines]) ->
lists:map(fun(L) -> maps:from_list(lists:zip(Head), L)) end, Lines).
Another language which works differently is Rebol: csv-to-maps: func [csv-data] [
map-each line next csv-data [map zipmap first csv-data line]
]
Whats interesting about above is that `first csv-data` will be re-evaluating on each `map-each` sequence. Of course you can assign to variable beforehand. Alternatively because code-is-data and vice-versa you can use COMPOSE it inline: csv-to-maps: func [csv-data] [
map-each line next csv-data compose [map zipmap (first csv-data) line]
]
:)NB. Rebol doesn't come with ZIPMAP so here's a definition for above to work:
zipmap: func [keys vals] [
collect [
forall keys [
keep reduce [keys/1 vals/(index? keys)]
]
]
] csv_data_to_maps([Head | Lines]) ->
lists:map(fun(L) -> maps:from_list(lists:zip(Head, L)) end, Lines).Then again with Python I'd just fire up NumPy or ugh Pandas(which is basically NumPy with benefits) for this kind of transformation.
I think it’s one of the reasons why people always say that learning Clojure makes them better developers even when they’re not using Clojure. The ideas that that take away from idiomatic Clojure and use in other languages.
I'm sure there are clever ways of accomplishing this in other languages, but the default way a Java/C# dev would probably approach this is to create a class that represents the CSV columns, and imperatively iterate over the contents.
With Clojure, the above function is idiomatic, and 4 lines long.
When it comes to "information processing" systems, which is what a lot of us work on, having a language with a primary purpose to provide powerful and concise tools to process that information is.. I don't know, liberating? (maybe not the best choice in words).
(this example was a bit of an eye-opener for me, coming from a .Net background, as I was writing some simple Clojure code that needed to read in some data and was struck at how simple this solution is)