lo icon indicating copy to clipboard operation
lo copied to clipboard

Curried map, reduce and filter for partial application

Open Southclaws opened this issue 2 years ago • 1 comments

I make use of partial application quite a lot, especially with lodash/fp, it's handy for building ad-hoc easily testable transformers.

Would be nice to see some added here! One repo that's growing out of #82 is dt where I'm dropping all these useful functions but it would be great to have it all in one place.

https://github.com/Southclaws/dt

An example of partial application would be:

func Map[T any, R any](iteratee func(T) R) func([]T) []R {
	return func(collection []T) []R {
		result := make([]R, len(collection))

		for i, item := range collection {
			result[i] = iteratee(item)
		}

		return result
	}
}

so the argument order is flipped and separated into two separate function calls. This allows you to "build" a "mapper": mapper := Map(someFunc) then re-use it later: updated := mapper(list)

Southclaws avatar Mar 20 '23 14:03 Southclaws

It is also possible to use something like it as well:


// uncurry helps to use lo.Map without providing an index to iteratee
func uncurry[T any, R any](f func(T) R) func(T, int) R {
	return func(t T, _ int) R {
		return f(t)
	}
}

To transform a mapper with type func (T) R into func(T, int) R type. An example on go.dev. Please ping me if anyone wants a PR for it. Not sure it will be accepted though. Still, qute handy and could be useful in many other places in lo.

image

itroot avatar Nov 29 '24 12:11 itroot