by eutectic · 9y ago · 0 comments
import Control.Monad (guard)
import Data.Ratio ((%))
results :: [[Int]]
results =
do th <- u
o <- u
r <- u
guard $ 2*th^2 + o^2 + r^2 == 1000
s <- u
z <- u
guard $ th^2 * z^2 * (s - z) + s^2 == 7225
g <- u
d <- u
xi <- u
guard $ (g - 1)^2 + d^2 + xi^2 - xi == 600
(et, i) <- [(xi - 7, xi - 11), (xi - 11, xi - 7),
(xi + 7, xi + 11), (xi + 11, xi + 7)]
guard $ 0 < et && et <= 26 && 0 < i && i <= 26
(a, mu) <- [(4, 1), (2, 2), (1, 4)]
pi <- u
guard $ a * (a + pi) == 4 * g
b <- u
n <- u
guard $ b^3 + z^3 + n^3 + o^9 == 1997
k <- [3, 4]
e <- u
guard $ (a % k)^2 + (b % n)^2 + (d % xi)^2 +
(e % pi)^2 + (et % mu)^2 + (i % s)^2 == 6
return [a, b, g, d, e, z, et, th, i, k, th, mu, n, xi, o, pi, r, s]
where u = [1..26]
main :: IO ()
main = print results for b in range(1, 27)
for n in range(1, 27)
if b**3 + z**3 + n**3 + o**9 == 1997
for k in (3,4)
for e in range(1, 27)
This reduces the number of innermost tests and on my laptop it runs about 18x faster than the blog's solution. That was: for k in (3,4)
for b in range(1, 27)
for e in range(1, 27)
for n in range(1, 27)
if b**3 + z**3 + n**3 + o**9 == 1997
Then I see that @eutectic did the same optimization in his Haskell code. Nice!This isn't an accident. Python's list comprehensions were modeled on Haskell's list comprehensions, which were in turn modeled on the much more general concepts of monads. Haskell's do notation provides a nice syntactic sugar for monadic code. Since lists form a monad, such code is quite naturally expressed using do notation.
Haskell's list comprehensions can be directly translated to do notation
[x+y | x <- [1..10], y <- [1..10], x+y<5]
can be translated into do x <- [1..10]
y <- [1..10]
guard (x+y<5)
return (x+y)
which is syntactic sugar for [1..10] >>= (\x ->
[1..10] >>= (\y ->
guard (x+y<5) >>
return (x+y)))
where (>>=) is the monadic bind operator.It's true that Python borrowed the concept from Haskell.
But Haskell in turn took the concept from set theory, not category theory.
List comprehensions are modeled after set comprehensions. Here's an example that uses set-builder notation [0] to define the set of Pythagorean triples with sides bounded by 10:
{ (x,y,z) | x,y,z \in {1,2,...,10}, x^2 + y^2 = z^2 }
In Haskell that becomes let u=[1..10] in [ (x,y,z) | x<-u,y<-u,z<-u, x^2 + y^2 = z^2 ]
The creators of Haskell worked hard to make sure the syntax was a spitting image of set theory.For a motivation behind the creation of Haskell was to use it to as a lightweight calculator / computer algebra system (sans heavy algebra) to teach set theory to students.
List comprehensions have been around since the dawn of Haskell. It was around even before Haskell, viz. in Miranda circa mid-80s.
Moggi's work on PL monads was only published in 1991.
I think you've mixed up monad comprehensions--which came much later--which is the observation that this notation and concept can be generalized to monads other than lists. Monad comprehensions segue into topos theory, understood as a monadic generalization of set theory, quite nicely.
Hopefully, the next 700 monad tutorials will give more visibility to topos theory.
It's so much easier to see all this by just working out a small example for yourself with pen and paper.
So these two are equivalent, and the list comprehension version is very close to what nested loops (read it from left to right) would give you, except for the laziness.
do x <- [1, 2, 3]; guard (f x); y <- [1, 2, 3]; guard (g x y); z <- [1, 2, 3]; guard (h x y z); return (x, y, z)
[(x, y, z) | x <- [1, 2, 3], f x, y <- [1, 2, 3], g x y, z <- [1, 2, 3], h x y z]
for x in [1, 2, 3] { if (f(x)) { for y in [1, 2, 3] { if (g(x,y)) { for z in [1, 2, 3] { if (h(x,y,z)) { yield((x, y, z)) }}}}}} -- "pseudocode"
The guard uses the following idea: guard True = [()]
guard False = []
So _ <- guard True is a noop, while _ <- guard False short-circuits the list comprehension the way "continue" would (just like "for x in [] { ... }"), so guard (f x) becomes the test f x in the list comprehension. (et, i) <- [(xi - 7, xi - 11), (xi - 11, xi - 7),
(xi + 7, xi + 11), (xi + 11, xi + 7)]
Could be written as (et,i) <- do (a,b) <- let tuple = (7,11) in [tuple, swap tuple]
sign <- [id,negate]
[(xi+sign a,xi+sign b)] guard $ (a % k)^2 + (b % n)^2 + (d % xi)^2 +
(e % pi)^2 + (et % mu)^2 + (i % s)^2 == 6
can be written as guard $ (6 ==) $
sum $ map (^2) $
zipWith (%)
[a ,b ,d ,e ,et,i ]
[k ,n ,xi,pi,mu,s ] sum $ map (^2)
Is pretty clear as a sum of squares is a quite common mathematical idiom. The zipWith part could probably be avoided. guard $ (6 ==) $
sum $ map (^2)
[(a%k),...]results is an array of Int, but do the double [[ ]] brackets mean something special? I hope they do, otherwise why planting doubts in people's mind.
<- is assignment or pattern matching, probably the latter.
the $ after guard is... what? Maybe a noop like Python's :
Maybe
guard $ expression
something
is equivalent to if expression
something
If this is the case, it's much less readable because people are left guessing. The lack of indentation doesn't help either.u is probably the variable that's iterated over in where u = [1..26]
Not very readable to put that after every use of u. This is easier to read
where u = [1..26] do
which is many languages is for u in [1..26] do
I can imagine that where is more general and is used in other contexts.Don't take these as criticisms of Haskell, only as a UX test. Python's list comprehensions have never been very readable to me. This Haskell loop is somewhat better.
I'm sure there are good reason for designing Haskell's syntax like that. Programming languages belong to lineages and tend to perpetrate the syntax of their parents. It makes them easier to adopt to developers well versed in their parent languages but that could also make them difficult to grasp for developers of other language families. Maybe luring imperative developers into the functional world is not one of the goals of Haskell and Haskell has achieved its goals as it is.
Still I believe that the first functional language that looks like an imperative language will move many developers from OOP to functional. Elixir attempted that, consciously or not, but it's not enough. The barrier there are the OTP patterns, which are not easy to use properly. There are many different choices for writing a process (what in OOP would be an object with its own CPU) and its hard to chose the proper one. GenServer, Agent, Task? Nobody is asking these kind of questions in Ruby or Python https://groups.google.com/forum/#!topic/elixir-lang-talk/DCT...
There is also the code to add them to the supervision tree (the cool systemd-inside-the-language thing of Erlang and Elixir). I can't help thinking that Elixir has to be streamlined.
Neither really, though I guess it's kind of like assignment, but it's usually read "draw from". Do-notation is sugar for working with monadic values, which are kind of like containers that hold a value. It's a bit hard to explain, but basically it means to pull the enclosed value out of the container on the right hand side and reference it according to the name on the left hand side.
> the $ after guard is... what?
$ is function application. It basically means to evaluate the right hand side before passing the result to the left hand side. It's used to avoid parentheses, `f $ g h` is like `f (g h)` (Haskell doesn't use parenthesis for function evaluation).
Haskell syntax is lovely when you're used to it, but it's also subtle. IMO it can be easy for people who aren't familiar to get the general idea of what's going on but the specifics are often not what you think.
Guard $ foo
Is equivalent to filtering out the values in u in each variable that fails foo. They're staged that way for the sake of performance - filter out possible values of x now so that the next guard statement has fewer possibilities to iterate over.Then, once all guard statements have been put into effect, the full set of combinations of values that pass each guard are placed in the array.
Critically, it is not "for u in [0..26]" but "u=[0..26]", which gives me the idea that this isn't a loop but a filter.
That's supposed to be the deal with javascript (but please don't ask me for a source; I was first introduced to the idea that js is functional in a book in an old workplace's library, where I was waiting for my boss to chew me up. Needless to say, I haven't used javascript much).
> where u = [1..26] do
This isn't valid Haskell, but this is
let u = [1..26] in
do ...
Also ($) is just sugar to avoid parenthesis.Instead of writing
f (1+2*3)
you can write f $ 1+2*3
Haskellers have a massive fetish for eliminating parenthesis, perhaps in order to avoid their code looking like lisp.This is because there could be more than one set of solutions to the simultaneous eqn