State monad vs atom in Clojure - clojure

Does state monad make any sense in Clojure? If so, I would appreciate cases where state monad will be more suitable than mutating Clojure atoms via swap!s or reset!s.

You won't bee needing it. But monads are used to build more involved abstractions than plain state. Clojure's core.async's go macro is a state machine and internally it's implemented as a monad. You can watch Tim Baldridge's explanation of it: https://www.youtube.com/watch?v=R3PZMIwXN_g

Monads makes sense if you would prefer to keep the code that way. You can have a (monadic) function which encapsulates state.

Related

Is there an idiomatic alternative to nil-punning in Clojure?

I'm reading some Clojure code at the moment that has a bunch of uninitialised values as nil for a numeric value in a record that gets passed around.
Now lots of the Clojure libraries treat this as idiomatic. Which means that it is an accepted convention.
But it also leads to NullPointerException, because not all the Clojure core functions can handle a nil as input. (Nor should they).
Other languages have the concept of Maybe or Option to proxy the value in the event that it is null, as a way of mitigating the NullPointerException risk. This is possible in Clojure - but not very common.
You can do some tricks with fnil but it doesn't solve every problem.
Another alternative is simply to set the uninitialised value to a symbol like :empty-value to force the user to handle this scenario explicitly in all the handling code. But this isn't really a big step-up from nil - because you don't really discover all the scenarios (in other people's code) until run-time.
My question is: Is there an idiomatic alternative to nil-punning in Clojure?
Not sure if you've read this lispcast post on nil-punning, but I do think it makes a pretty good case for why it's idiomatic and covers various important considerations that I didn't see mentioned in those other SO questions.
Basically, nil is a first-class thing in clojure. Despite its inherent conventional meaning, it is a proper value, and can be treated as such in many contexts, and in a context-dependent way. This makes it more flexible and powerful than null in the host language.
For example, something like this won't even compile in java:
if(null) {
....
}
Where as in clojure, (if nil ...) will work just fine. So there are many situations where you can use nil safely. I'm yet to see a java codebase that isn't littered with code like if(foo != null) { ... everywhere. Perhaps java 8's Optional will change this.
I think where you can run into issues quite easily is in java interop scenarios where you are dealing with actual nulls. A good clojure wrapper library can also help shield you from this in many cases, and its one good reason to prefer one over direct java interop where possible.
In light of this, you may want to re-consider fighting this current. But since you are asking about alternatives, here's one I think is great: prismatic's schema. Schema has a Maybe schema (and many other useful ones as well), and it works quite nicely in many scenarios. The library is quite popular and I have used it with success. FWIW, it is recommended in the recent clojure applied book.
Is there an idiomatic alternative to nil-punning in Clojure?
No. As leeor explains, nil-punning is idiomatic. But it's not as prevalent as in Common Lisp, where (I'm told) an empty list equates to nil.
Clojure used to work this way, but the CL functions that deal with lists correspond to Clojure functions that deal with sequences in general. And these sequences may be lazy, so there is a premium on unifying lazy sequences with others, so that any laziness can be preserved. I think this evolution happened about Clojure 1.2. Rich described it in detail here.
If you want option/maybe types, take a look at the core.typed library. In contrast to Prismatic Schema, this operates at compile time.

What is the use of monads in OCaml?

This might be a stupid question, but since OCaml is not pure and has side effects built-in, what is the use of monads in OCaml?
Monads have nothing to do with purity, except that a pure language without Monads would be almost entirely useless.
In layman's terms, a Monad is just a set of rules that describe how a sequence of steps can be executed. Having a Monad abstraction gives you the ability to define a DSL for executing stuff. A Monad can be built to intelligently handle things like exceptions, ATOMIC rollbacks/commits, retry logic, sleeping between each step, or whatever.
Here are some examples of Monads:
https://wiki.haskell.org/Monad#Interesting_monads
I realize that this list is for Haskell, which is a pure language, but don't let that confuse you.
You don't need to understand category theory to understand what a Monad is, contrary to popular belief. A monad basically has 2 things: (paraphrased from this wikipedia article)
A unit function, defined as (a -> M a), called "return" in Haskell, used to put a value into the context of a Monad.
A binding operation, defined as (M t -> (t -> M u) -> M u), which looks scary but if you look carefully, this is a function that gets invoked between each step of the process, this is where you inject the good stuff.
Depending on the language, there may be more things, but this is the heart of it.
Whilst OCaml supports the standard side-effects provided by most languages, this does not include all possible side-effects. There are a number of effects which OCaml does not provide native support for. Many of these effects can be encoded using Monads. For example,
Concurrency (see Lwt and Async libraries)
Non-deterministic choice
First-class continuations
Ambivalent choice and backtracking
Using more sophisticated representations of computation, such as parameterised monads, even more exotic effects can be encoded. For example,
Polymorphic state
Linear resources
While OCaml allows one to write imperative code it is still functional by its nature, it is used by functional programmers. And we prefer to use persistent data structures and algorithms whenever possible.
What concerning your question, then in particular monads are usefull, for asynchronous computations, e.g., Lwt, Async, where they're used to bind computations (instead of usual way of setting callbacks). Also, monads are used for error handling, instead of exceptions. Also, monads are very helpful in writing parsers, see mparser library. There're also other uses, I enumerated only the most popular.
In general monads just allow you to hide a complex control flow under simple sequential syntax.
This may be a lot more naive than the answer you want but a monad is just a simple abstraction that's useful for structuring computation. It's a little math thing like an equivalence relation (or for people smarter than I am, like a group). Once you learn what they are, you see them everywhere, and they help organize your thinking.

Can I use monads with clojurescript?

I know monads are available in clojure, but has anyone verified that they work in clojurescript?
Monads work in clojurescript. The only thing is the way you reference macros in clojurescript [1].
What I did is copy all tools/macro.clj and all the monads.clj code into a big file which I then reference from clojurescript.
It's perhaps not the most elegant way but it works.
You can find the file in https://github.com/cotarmanach/clojurescript-monad-macros
(I copy it in my project and change the namespace to be the one of my project)
[1] See https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure
ClojureScript's macros are written in Clojure, and are referenced via
the require-macros keyword in namespace declarations:
(ns my.namespace (:require-macros [my.macros :as my])) The :as
prefix selector is required in :require-macros. One point of note is
that the code generated by ClojureScript macros must target the
capabilities in ClojureScript.
Monads, the Functional programming method, only require a language with higher order functions and closures. You would need a ClojureScript monad library. Or you can go ahead and write your ClojureScript in a monadic style
EDIT: by "monadic style" I was referring to writing and composing functions that take and return monadic values and implement the three monad laws. There are too many people better qualified to explain monads than I, so I will just link to one of my personal favorite videos on monads.
There is a great port of the Fluokitten Library to ClojureScript by Chris Zheng: https://github.com/purnam/brahmin
Chris has a great post reflecting on Monads as a result of this.
The cats library for Category Theory is also good https://funcool.github.io/cats/latest/
Monads in ClojureScript is alive and well.

Methods for side-effects in purely functional programming languages

At the moment I'm aware of the following methods to integrate side-effects into purely functional programming languages:
effect systems
continuations
unique types
monads
Monads are often cited to be the most effective and most general way to do this.
Which other methods exist? How do they compare?
Arrows, which are more general than monads.
The very simplest method is to simply pass around the environment between the functions. This is often used to teach scheme.
To me a more general way is via a monad/comonad pair. This generalizes the common "monad" approach which should correctly be called the "strong monad" approach, since it only works with strong monads.
Moving to a monad/comonad pair allows effects to be modeled that result in some variables no longer being available. An example where this is useful is the effect of migrating a thread to another host in a distributed setting.
An additional method of historical interest is to make the whole program a function mapping a stream/list of input events to a stream/list of output events. See: "How to Declare an Imperative" by Phil Wadler: http://www.cs.bell-labs.com/~wadler/topics/monads.html#monadsdeclare

When should I use deftype in Clojure?

Yesterday, Rich pulled the 'new' branch of Clojure into master. We are now embracing the beauty that is deftype and defprotocol. Of course, I, coming from Haskell, am very tempted to define types like I would in Haskell, which would be for virtually everything short of a throwaway tuple, but I don't think it works like that in Clojure world ;). In the Common Mistakes thread for Clojure, one guy mentioned that overusing structs was a mistake he made when he first started, coming from OOP. Since deftypes seem to be similar to structs, I was wondering if the same thing applies there.
So, my question is: when is it a good time to use deftype?
One area deftype shines is performance. Methods of protocols are very fast on a deftype. Also deftype may have primitive fields, so no boxing anymore when crunching numbers...
Another area might be Java interoperation, since deftype can implement interfaces (and if AOT compiled) have a named class.
In general is the basic idea to define abstractions with protocols and to implement them with deftype.
Rich details his motivation here: http://www.assembla.com/wiki/show/clojure/Datatypes