tyro
Is there a way to pipe the cons (list prepend) operator?
You can prepend to a list with:
[item | list]
But is it possible to pipe this operation? I can’t see any way to do this in List/Kernel, and there seems to be very little info about the cons operator in general. I would like to be able to do something like:
list
|> List.prepend(item)
Of course, I could use a custom/anonymous function but is there an inbuilt way to do this?
Most Liked
Qqwy
Elixir, Erland and Prolog use structural pattern matching, while Haskell uses staticly typed pattern matching.
These are similar, but not the same. For instance, in Haskell you cannot re-use the same name twice to say that two things are equal, you will have to use a guard.
I think this is at least a partial reason.
tyro
Thanks. Perhaps I should be clearer that I’m not looking for alternatives (I’m aware of insert_at), I just want to know if this exact feature exists. Cons is one of the most common operations in Elixir, and piping is similarly ubiquitous, so it would seem odd if you can’t use both together! ![]()
peerreynders
As far as I can tell:
- Erlang doesn’t actually have a cons “operator” but syntax for a cons cell i.e.
[ term1 | term2 ]- and it actually has two distinct uses, to construct a cons cell and to match a cons cell. So it makes sense that it is a language feature rather than an operator backed by a function. - Elixir and it’s macro support build on Erlang but the primary objective of the Pipe macro is to take the result of the preceding expression (LHS) and thread it into the first parameter of the next function (RHS) (Clojure actually refers to something like this as the thread first macro rather than a “Pipe”).
So the two simply don’t mix because Erlang’s cons cell predated Elixir and Elixir’s Pipe was designed to work with functions.
Always inquire whether there is an idiomatic way of doing things as commonality makes everybody’s life easier but also realize that sometimes the DIY-as-required approach is often accepted/preferred in order to keep clutter out of the language/platform.
Last Post!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security










