# How to write a function that outputs the linear combination of other functions?

**URL:** <https://discourse.julialang.org/t/how-to-write-a-function-that-outputs-the-linear-combination-of-other-functions/117740>\
**Category:** General Usage\
**Created:** [August 1, 2024, 6:32pm UTC](https://discourse.julialang.org/t/how-to-write-a-function-that-outputs-the-linear-combination-of-other-functions/117740 "2024-08-01T18:32:45Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [August 1, 2024, 6:55pm UTC](https://discourse.julialang.org/t/how-to-write-a-function-that-outputs-the-linear-combination-of-other-functions/117740/3 "2024-08-01T18:55:06Z")

</div>

> [@matthias314](#):
>
> What about putting coefficients and functions into a new type?

No new type needed. You can also get type-stable code with:

```julia
linear_combinations(f, c) = (x...; kw...) -> map(c, f) do c, f
    c*f(x...; kw...)
end |> sum

```

Defining new callable types (“functors”) can be useful for other reasons, of course; see [How are functors useful? - #6 by stevengj](https://discourse.julialang.org/t/how-are-functors-useful/24110/6)

The trick here is that you construct tuples from tuples (`map` has specialized methods for tuples), rather than generators `foo for (c, f) in zip(...)`. I believe `zip` by itself is also type-unstable for heterogeneous tuples, for that matter.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-write-a-function-that-outputs-the-linear-combination-of-other-functions/117740)._
