Qqwy

Qqwy

TypeCheck Core Team

Today I realized that it would be possible to implement currying-capability in Elixir, using some clever anonymous function creation. (‘continuation-style currying’).

There was already a library called curry, which required you to define your to-be-curried functions using a special macro. And it would then define 255(the max. arity in Elixir) different function heads for it.

Currying does not do that. Instead, when yo u call curry, the passed function is wrapped in an anonymous function accepting a single parameter. This anonymous function is constructed in a clever way that will re-construct a new anonymous function each time an argument is passed, until the original function’s arity is reached, in which case the original function is called and the result returned.

There’s also some niceties like curry_many which allows you to pass in a list of arguments to apply to a curried function at the same time, and an optional implementation of ~> as infix-variant of curry/2.

An example:

      iex> use Currying
      iex> enum_map = curry(&Enum.map/2)
      iex> partially_applied_enum_map = enum_map.([1,2,3])
      iex> results = partially_applied_enum_map.(fn x -> x*x end)
      [1,4,9]    

See the Currying library/hex package here!


I’d be very grateful for any feedback ;-).

Showing Posts 1 to 10

matteosister

matteosister

Awesome! I created a library for currying php functions, inspired by the incredibile mind blowing thing that haskell has been for me. I really love the concept of partial application and curry. Going to check it out for sure!

themarlzy

themarlzy

For the ignorant, what’s the point of currying functions? What’s a use case that it solves for?

NobbZ

NobbZ

Currying plus partial application is just awesome, and after having used some haskell you do miss it really hard everywhere else.

Since I haven’t take a look into @Qqwy’s currying package so far, I will give the examples in haskell.

Given the funtion foldr defined as this:

foldr f z []     = z 
foldr f z (x:xs) = f x (foldr f z xs) 

now your job is to implement map on top of this:

You can use either the very naïv approach to just write it down as this:

map f xs = foldr (\y ys -> f x : ys) [] xs

This is a fully applied function but can be further reduced (eta-reduced to be specific) to the following:

map f = foldr (\x xs -> f x : xs) []

After one gets used to it, it is just cool, but maybe, if you do not know it already, you will probably never miss it :wink:

Something in Elixir we could do with currying might look like this (untested):

use Currying

def const(a, _b), do: a

curried_const = curry(&const/2)
Enum.map([1,2,3,4,5,6,7,8,9,10], curried_const.(5))

# without curried:
Enum.map([1,2,3,4,5,6,7,8,9,10], &const(5, &1))

I have to admit, in elixir it looks quite a lot more clear and readable, even more idiomatic to simply use a capture :wink:

I think it is nice to play with currying and partial application in elixir, but I might probably stick with pipes and captures, since they are a native language thing, while the curried stuff feels foreign.

Qqwy

Qqwy OP

TypeCheck Core Team

Basically: You can only use captures if you exactly know how many arguments you’re going to put in your function right now. In the case of partial application (which might happen in multiple steps), this becomes a problem.

Currying means that you can treat all kinds of functions as unary (taking a single parameter) functions. This allows you to pass them around to higher-order functions (functions that take functions as input). It means that these higher-order functions only have to worry about manipulating unary functions, instead of functions of any arity.

In essence, currying lets you delay the ‘capture’ step to at runtime, instead of having to be defined in your source code.

It is the kind of thing that you will probably not miss when you don’t know about it. On the other hand, there are certain situations that are unsolvable, unless you can curry.

The main reason why I created this library, is that I had such need myself. I am working on another library, called fun_land (it isn’t on Hex yet as it is still unfinished), which creates algebraic data types (basically, ‘containers’ for other kinds of data).

NobbZ

NobbZ

Oh yeah! Now things are getting interesting! Any of the (for haskellers) well-known interfaces that carry over? Monads, Applicatives, other nice stuff?

Qqwy

Qqwy OP

TypeCheck Core Team

Yes! I am going the full way, implementing behaviours for semigroups and monoids, reducable and traversable, functors, appliable functors, applicative functors, chainable functors, monads and monad-monoids (known in Haskell as MonadPlus).

Starting with a clean slate means that there are many things that many of the duplicates that were the result of Haskell’s functors being ‘reverse engineered’ like Applicative pure== Monad return, Monad >>==Applicative *>, liftAvs liftM, MonadPlus mzerovs Monoid memptyetc. that can be unified, making it a whole lot more transparent what is going on.

I am am also going to rename some things, to make it as approachable as possible for people new to algebraic data structures. (such as Mappable instead of Functor, Combinable instead of Monoid, wrap instead of return).

Oh, and there are explanations about the different data types involving fruit salad. :grinning:

The inspiration for the library comes from a JS specification called fantasy land.

If you’d like to check the still-unfinished library out and maybe add some feedback, or point out things that are unclear, you can find FunLand on GitHub :slight_smile: .

peerreynders

peerreynders

Don’t you find that the design of the elixir standard library somewhat limits the usefulness of currying?

Typically elixir functions expect the data structure in the first parameter position - and the ubiquitous pipe operator exploits that fact. In Haskell the design pressure of “currying by default” leads to the last parameter position being ideal for the data structure.

That being said partial function application is still tremendously useful.

Qqwy

Qqwy OP

TypeCheck Core Team

Don’t you find that the design of the elixir standard library somewhat limits the usefulness of currying?

Yes, you are right. Many functions in Elixir put the ‘most important argument’ at the front for this reason. This is often the parameter that changes the most.

Maybe there is a way to create a currying-like function that leaves the first argument open, although this might be a bad idea as it does not seem very idiomatic to me.

On the other hand, Currying does allow you to do things like:

use Currying

list = [1,2,3,4]

&Enum.into/3
|> curry(list)
|> curry(%{}) 
|> curry(fn x -> {x, x*x} end)
peerreynders

peerreynders

Given that this is just part of your larger effort I think you need to stick with what you have - it’s just that there is going to be an “impedance mismatch” with functions originating from the outside of your library as they are going to apply different criteria for the ordering of their function parameters (including possibly default parameters).

I was talking more about the usefulness of curried functions in isolation, in an environment that doesn’t default to it. In Haskell curried functions seem to be a result of a focus on single parameter functions, i.e. functions that compose easily; curried functions in essence seem to supply a mechanism that allows functions to be “configured” one-parameter-at-time via partial application until they can become part of a function composition (ultimately driving towards the Pointfree style).

So given the process of curried functions being the first step towards function composition I would expect in Elixir “the spirit of currying” to drive toward a pattern like

result = data_struct |> fn1pa |> fn2pa |> fn3pa

which may be useful when the functions in the composition aren’t “configured” (partially applied) inside the current function’s closure.

But within the context of your larger library the goals seem to be entirely different.

OvermindDL1

OvermindDL1

Yeah I was thinking of the ‘most changing argument being in first position in Elixir’ too, it is the one big big thing that has bugged me from coming from Erlang, the most changing argument SHOULD be in the last position.

However, the curry could always build things in reverse maybe? Or just special code to put the last argument as the first in the actual call?

EDIT: And on a side note, the most changing argument in last position is a BEAM thing too, the BEAM can optimize function calls that have matching head arguments better than it can matching tails (if the head differs then it has to rebuild the entire argument list instead of being able to re-use the start, yes it is different from how Lists work).

Where Next? Top

Trending in Announcing Top

woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
fuelen
Hi all! I want to present a small library which provides a mix task for generating an Entity-Relationship Diagram for Ecto schemas. You...
New
anuaralfetahe
Hello Published a new library - ProcessHub! ProcessHub is a library designed to manage process distribution within the Elixir cluster. ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
AstonJ
This showed up on my feed.. anyone heard of it? Just hype? Ox Alpha is a reasoning model designed for coding, sustained ag...
New
sergio
It’s not that it’s vocabulary is too advanced. It’s something worse. I get lost trying to follow even a paragraph written by Claude. It’...
New
sorenone
Today we’re releasing Oban for Python. Not an Oban client in Python. Not a pythonx wrapper embedded in Elixir. Nope, it’s a fully operati...
New
akoutmos
@hugobarauna, Dr. Dimitrios Koutmos (my brother) and I (Alex Koutmos) have been hard at work on writing a book on how you can use Elixir ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews