# Implementation of a parametrized objective function without using module variables or internal subroutines

**URL:** <https://fortran-lang.discourse.group/t/implementation-of-a-parametrized-objective-function-without-using-module-variables-or-internal-subroutines/9919>\
**Category:** Uncategorized\
**Created:** [July 13, 2025, 3:28am UTC](https://fortran-lang.discourse.group/t/implementation-of-a-parametrized-objective-function-without-using-module-variables-or-internal-subroutines/9919 "2025-07-13T03:28:14Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![zaikunzhang](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/zaikunzhang/32/785_2.png) [@zaikunzhang](https://fortran-lang.discourse.group/u/zaikunzhang)\
**Post date:** [July 14, 2025, 6:25am UTC](https://fortran-lang.discourse.group/t/implementation-of-a-parametrized-objective-function-without-using-module-variables-or-internal-subroutines/9919/20 "2025-07-14T06:25:48Z")

</div>

Hi @certik . Maybe I have not emphasised the following point enough:

**The solver is provided by another library that cannot be modified by me. The interface of the solver is fixed as `solver(objective)`, and that of the objective is fixed as `objective(x, f)`.**

The question is essentially: what if I have an objective whose signature is `bla(x, f, hyper_parameter)`, where `hyper_parameter` is unknown before the program starts? In other words, what if the implementation yof the objective depends on hyperparameters that are unknown beforehand? How to optimise such an objective using `solver`?

See my code above for details. See a [similar example](https://fortran-lang.discourse.group/t/is-creating-nested-subroutines-functions-considered-good-practice-in-fortran/6545/17) of root finding by @ivanpribec in a [previous discussion](https://fortran-lang.discourse.group/t/is-creating-nested-subroutines-functions-considered-good-practice-in-fortran/6545) if mine is not clear enough; see also the example in Note 12.18 on page 290 of WD 1539-1 J3/10-007r1, F2008 Working Document. As an example mentioned in the standard, it is not a wired situation but a common use case.

My approach is to use an internal procedure as you mentioned. But this leads to executable stack, which is a security issue. It is not allowed on some systems, and it causes a segfault of MATLAB R2025a.

Another approach is to pass the hyperparameter using a module variable, but it is not thread-safe or recursion-safe?

Is it possible to have a standard-confirming implementation that is thread-safe without internal procedures?

---

_[View the full topic](https://fortran-lang.discourse.group/t/implementation-of-a-parametrized-objective-function-without-using-module-variables-or-internal-subroutines/9919)._
