13 ms·
Comparison of Haskell and Julia List Comprehensions
- occamrazor 5y agoJulia’s syntax is the same as Python’s. It’s very natural for short expressions, a bit cumbersome for multiline comprehension, because there is no obvious way to format the code. Another gripe I have is the order of the for clauses: [x for xs in xss for x in xs] should, in my opinion, be instead written as [x for x in xs for xs in xss] Also Haskell gets the order of ‘<-‘ clauses wrong, so probably mine is a minority opinion.
- jolmg 5y ago> Also Haskell gets the order of ‘<-‘ clauses wrong, so probably mine is a minority opinion. That's probably so it's more in-line with do-notation: [x | xs <- xss, x <- xs] is the same as: do { xs <- xss; x <- xs; return x } Maybe writing statements backwards was deemed more confusing. Personally, I don't really use list comprehension syntax, but maybe I would if they were backwards like you describe. It would make more sense with the position of the return value being to the left.
- berlinquin 5y agoI can make sense of nested Python list comprehensions if I read them as shorthand for nested for loops, in which case you need to define variables in the outer loop before you can define dependent variables in the inner loop. e.g. with your example above, for xs in xss: for x in xs: x What's confusing about the syntax is that `x` in your example above comes first, whereas in actual nested loops it comes last. So maybe: [for xs in xss for x in xs : x] Could be alternative syntax that moves `x` to the end?
- shirogane86x 5y agoThat's actually how list comprehensions work in F#: that would become: [for xs in xss do for x in xs -> x] (where -> is a shorthand for do yield) in practice (after 3 years of professional F#), when writing functional code i'd actually rather have the result first rather than last. I got used to reading code right to left with Haskell so that's what feels most natural to me
- BadInformatics 5y agoNote that because blocks in Julia are expressions, you can do multi-line expressions in comprehensions that you wouldn't be able to do in Python: [ let y = x + 1 z = 2y -z end for x in 1:5 ]
- dmitriid 5y agoHaskell and Erlang basically go for mathematical notation. Python and Julia more or less go for how you read those notations. I personally prefer math-like notation because I find it much more readable and composable. x, such as x is in xs, xs is in xss x | x ∈ xs, xs ∈ xss # my math is rusty [x | x <- xs, xs <- xss] # haskell, erlang is isimilar [ x for xs in xss for x in xs ] # python, julia, order might be different As soon as you add conditions/filters on data, math-like notation wins hands down Edit: Since I don't know Haskell, apparently in Haskell the order is wrong. So, only Erlang gets it right (variables are upper case in Erlang): [ X || X <- Xs, Xs <- Xss]
- jolmg 5y ago> only Erlang gets it right... [ X || X <- Xs, Xs <- Xss] I don't have much experience with Erlang, but that also seems wrong: 1> Xss = [[1]]. [[1]] 2> [ X || X <- Xs, Xs <- Xss]. * 1:13: variable 'Xs' is unbound 3> [ X || Xs <- Xss, X <- Xs]. [1]
- dmitriid 5y agoDamnit. I haven't used Erlang in a long time, but I should've known that. So, no language does it "right".
- sundarurfriend 5y agoNote that in Julia, ∈ is a synonym of `in`, so a minor improvement towards your preferred notation can be: [ x for xs ∈ xss for x ∈ xs ]
- romwell 5y agoI'm with you on that minority opinion. The "for" side mimics nested for loops structure, but then the output statement goes first (?!). It's the same feel as MM/DD/YYYY date format: very widespread, yet absolutely asinine to anyone seeing it for the first time :)
- smegma2 5y agoI thought the same about the ordering but on the other hand this order matches what you would write in the imperative case i. e. for xs in xss: for x in xs: ...
- zem 5y agoafter many, many years of writing python i still get this wrong at times, because i instinctively expect `[x for x in xs for xs in xss]` to be the correct version!
- tpoacher 5y agoI appreciate where you're coming from, but this particular order allows you to reuse a variable. E.g, in earlier pythons which didn't yet have ":=", the example given by the comment below yours could be written as: [ z for x in range(1,6) for y in [x+1] for z in [2*y] for z in [-z] ] Obviously not the kind of style you'd want to see in written code, but ...
- maweki 5y agoIs Julia eager? In Haskell you can also do infinite lists [1..] This generates all the integers. The first example [ x^2 | x <- [1..5] ] Is basically already list comprehension within list comprehension. Are infinite lists possible?
- bobbylarrybobby 5y agoJulia’s Iterators package has infinite iterators but I don’t think there’s syntax for them
- oscardssmith 5y agoIf you use parens instead of brackets, you get lazy comprehensions in Julia.
- montalbano 5y agoNote that in Julia these are often referred to as array comprehensions, as the data structure involved is a (very efficient) array. C.f. Python
- kryptiskt 5y agoAnd in Haskell they are monad comprehensions these days, so they can build more than lists. They actually used to be so back in the 90s, but Haskell 98 was conservative and restricted them to lists.
- exdsq 5y agoWhat do monad comprehensions offer?
- thewakalix 5y agoList comprehensions are a concise way of writing do-expressions in the list monad, so monad comprehensions just extend that to all monads.
- jolmg 5y agoBeing very generic. One can define a very efficient array structure, define its Monad instance and be able to use it in comprehensions. The point is that comprehensions are not fixed to a particular data structure by the language, and can be used with any user-definable Monad.
- dwohnitmok 5y agoHaskell's comprehension syntax is very powerful and quite a bit more general than what is described here. It can both be generalized to arbitrary monads through `MonadComprehension` and has extended syntax that brings in basic SQL operators (such as grouping and sorting) through `TransformListComp` as well as zipping through `ParallelListComp`. The links are respectively https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/monad_comprehensions.html https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/mona..., https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/generalised_list_comprehensions.html https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/gene..., and https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/parallel_list_comprehensions.html https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/para.... And what's more is that all three of these play very nicely with each other, so that you can write SQL-like syntax to deal with say an arbitrary, side-effectful stream rather than a finite data structure. That means you can write something like (to take the example from the `TransformListComp` docs) output = [ (the dept, sum salary) | (name, dept, salary) <- employees , then group by dept using groupWith , then sortWith by (sum salary) , then take 5 ] where `employees` is e.g. a paginated HTTP endpoint that you're hitting. It can make for some very nice code.
- mbauman 5y agoConversely, Julia's comprehension syntax is very powerful and quite a bit more general than what is described here — but in a different way. - They're not list comprehensions, they're one-dimensional vector comprehensions. And they seamlessly extend to multidimensional array comprehensions. - Just drop the square brackets and instead of a dense array you get a lazy generator!
- anyfoo 5y agoCorrect me if I'm wrong, but doesn't them being Monad comprehensions in Haskell automatically mean that Haskell's "list" comprehensions can be all of those things as well, and more? As well as the language's laziness by default that pretty much encompasses the generator aspect in general anyways. (Although I'm not really trying to pit anything against each other here, they are different languages with different requirements.)
- codesections 5y agoThe Raku syntax for list comprehension[0] is very similar as well. Julia: [ x^2 for x = 1:5 ] Raku: do $_² for 1..5; [0]: https://docs.raku.org/language/py-nutshell#List_comprehensions https://docs.raku.org/language/py-nutshell#List_comprehensio...
- tikhonj 5y agoOne feature I rather like in Haskell is being able to zip with list comprehension syntax[1]: λ> [(x, y) | x <- [1..] | y <- [1..3]] [(1,1),(2,2),(3,3)] This example is a bit silly—I would just write zip [1..] [1..3]—but it makes more complex expressions involving zips much easier to read at a glance. I looked through some real code I've written, and being able to do things like this is definitely nice: toHashMap values = HashMap.fromList [ convert name value | name <- Schema.fldName <$> Schema.fields t | value <- Vector.toList values ] Of course, this particular example would be nicer if Haskell had something like dictionary comprehensions for building hash maps, but this isn't an awful substitute, and zipping multiple sequences together is useful in a lot of other configurations as well! [1]: I should add that this requires enabling the somewhat misleadingly named `ParallelListComp` extension. Frankly, I think extensions like this should just be added to the language—this introduces new syntax, so it never changes previously valid code—but the Haskell community is very conservative about making changes to the core, standardized part of the language :/.
- ssivark 5y agoThat actually seems confusing. I would normally expect such code to perform a Cartesian product i.e. all pairs of (x,y).
- dwohnitmok 5y agoIt would be a Cartesian product if the second `|` was changed to `,` (as is the case in the article and most examples in this comment section).
- moomin 5y agoI mean, the irony here for me is that I regard Haskell's list comprehensions as a bit of a bag on the side. There's not much that couldn't be equally readably implemented using other Haskell syntax.
- DNF2 5y agoAre there multidimensional comprehensions in Haskell? In Julia you have jl> [ (x,y) for x in 1:3, y in 2:5 ] 3×4 Matrix{Tuple{Int64, Int64}}: (1, 2) (1, 3) (1, 4) (1, 5) (2, 2) (2, 3) (2, 4) (2, 5) (3, 2) (3, 3) (3, 4) (3, 5)
- jolmg 5y agoYou can have them if you can define Matrix as a data structure with a Monad instance. I don't know if there are any packages that do something like that. Maybe something roughly like this: data Matrix a = Matrix { matrixDimensions :: [Int] , matrixCells :: [a] } deriving (Show) fromList :: [a] -> Matrix a fromList xs = Matrix [length xs] xs instance Functor Matrix where fmap f (Matrix dims xs) = Matrix dims $ fmap f xs instance Applicative Matrix where pure x = Matrix [] [x] Matrix fds fs <*> Matrix xds xs = Matrix (fds ++ xds) (fs <*> xs) instance Monad Matrix where Matrix ds xs >>= f = Matrix (ds ++ rds) rs where Matrix rds rs = case f <$> xs of [] -> Matrix [] [] ms@(Matrix frds _:_) -> Matrix frds (concat $ matrixCells <$> ms) ghci> [(x, y) | x <- fromList [1..3], y <- fromList [2..5] ] Matrix {matrixDimensions = [3,4], matrixCells = [(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,2),(3,3),(3,4),(3,5)]} If you want it to be pretty printed into a nice-looking table, you can define your own Show instance. This is probably not the best way to implement it, though. Notice that I use the first Matrix returned by `f` in the Monad instance definition and assume that all subsequent matrices are of the same dimensions. The problem with fixing that is that we'd have to fix the dimensions into the type and that would prevent us from writing a Monad instance that would work for your example. I don't know Julia, but I think the reason why this is not a problem for it is because neither x nor y are in scope for each other's definition: julia> [ (x,y) for x in 1:3, y in 1:x ] ERROR: UndefVarError: x not defined Stacktrace: [1] top-level scope @ REPL[1]:1 julia> [ (x,y) for x in 1:y, y in 1:3 ] ERROR: UndefVarError: y not defined Stacktrace: [1] top-level scope @ REPL[2]:1 while x would be in scope for y's definition in Haskell, allowing the y dimension to vary by value of x. I guess the best one can do in terms of safety for that case is turn it into a runtime error in Haskell. If one wants to handle Matrices with better type-safety it's probably best to give up on comprehensions for it, make the Matrix type more descriptive, and use other operators.
- moonchild 5y agoAPL has no list comprehensions, but can generally be as clear and concise (if not more so) using ordinary array operations. Re-implemented: 2*⍨⍳5 1 2 3 ∘., 4 5 (⊢,¨⊢+∘⍳1+3-⊢)¨1 2 3 ⍝ok, this one is not so hot, but apl has no primitive for x..y concat ← ∊ ⍝primitive firsts ← ⊃⍤¯1 ⍝leading-axis version firsts ← ⊃⍤1 ⍝trailing-axis version firsts ← ⊃¨ ⍝nested version length ← +/1⍨¨ ⍝this counts! factors ← ⍸0=⍳|⊢ ⍝doesn't include the number itself prime ← (,1) ≡ factors primes ← (prime⍤0{⍺/⍵}⊢)⍳ ⍝{⍺/⍵} is a historical artefact, please ignore it find ← (1⌷⊢){⍺/⍵}⍨9=0⌷⊢ ⍝{⍺/⍵} is very sorry for its repeat appearance pairs ← 2 ,/ ⊢ sorted ← ∧/ 2≤/⊢ positions ← ⍸= is_lower ← {sorted ⎕ucs 'a'⍵'z'} lowers ← +/(is_lower⍤0) count ← +/= Note many of these are polymorphic wrt rank (or can trivially be made so), where the haskell and julia implementations only work on rank-1 ([a]) or rank-2 ([[a]]) arrays.
- dwohnitmok 5y agoThe Haskell one is polymorphic with respect to rank (and is indeed polymorphic even with respect to whether it's backed by a data structure or not). Haskell's infelicities for numeric code come from other places.
- moonchild 5y agoFor those haskell functions which operate on lists of arbitrary items, the items can indeed be themselves lists. However, the code is still fundamentally item-oriented. Those haskell functions which operate on lists of specific types (such as 'lowers', which operates on lists of characters) cannot readily be applied to higher-ranked lists of the same.
- dwohnitmok 5y agoI suspect you mean `toLower`? In that case yes it can (and again generalized to many other contexts rather than just higher dimensional data structures), you just use lifted function application (that is `<$>`) instead of normal function application (that is `$`). (The item-oriented way of thinking about this, which is equivalent, is you use `fmap`).