将函数传递给子例程时,伪过程“f”中的接口不匹配 [英] Interface mismatch in dummy procedure 'f' when passing a function to a subroutine

查看:136
本文介绍了将函数传递给子例程时,伪过程“f”中的接口不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个有两个参数的子程序(用于最小化):
$ b $ ul
<数组 x任何长度的

  • 一个函数 f ,它接受一个长度的数组并返回一个标量 li>


    示例模块:

      module foo 

    包含

    子例程solve(x,f)
    real,dimension(:),intent(inout):: x
    接口
    实数纯函数f(y)
    导入x
    实数,维数(size(x)),intent(in):: y
    结束函数
    结束接口

    print *,x
    print *,f(x)
    结束子程序

    结束模块

    和测试程序:

     使用foo 

    real,dimension(2):: x = [1.0,2.0]

    解析(x,g)

    包含

    真实纯函数g(y)
    实数,维(2),意图(in):: y

    g = sum(y)
    end功能

    结束

    gfortran失败:

     调用solve(x,g)
    1
    错误:虚拟过程'f'在(1)处的接口不匹配:Shape如果我更改 size(x),那么参数'y'的第1维不匹配

    )=> 2 然后编译(并运行)很好。如果我更改:=>,它也可以正常工作。 2 。但这些解决方案都不能满足我的需求。

    关于我如何实现这一点的任何想法?

    解决方案

    如何:

      interface 
    真正的纯函数f(y)
    实数,维(:),intent(in):: y
    结束函数
    结束接口

    当您将函数 solve 的参数传递给函数时,该数组将自动被传递。你不需要做这部分界面。


    I am trying to write a subroutine (for minimisation) that has two arguments:

    • an array x of any length
    • a function f that takes an array of that length and returns a scalar

    example module:

    module foo
    
    contains
    
      subroutine solve(x, f)
        real, dimension(:), intent(inout) :: x
        interface
          real pure function f(y)
            import x
            real, dimension(size(x)), intent(in) :: y
          end function
        end interface
    
        print *, x
        print *, f(x)
      end subroutine
    
    end module
    

    and test program:

    use foo
    
    real, dimension(2) :: x = [1.0, 2.0]
    
    call solve(x, g)
    
    contains
    
      real pure function g(y)
        real, dimension(2), intent(in) :: y
    
        g = sum(y)
      end function
    
    end
    

    gfortran fails on:

    call solve(x, g)
                  1
    Error: Interface mismatch in dummy procedure 'f' at (1): Shape mismatch in dimension 1 of argument 'y'
    

    If I change size(x) => 2 then it compiles (and runs) fine. It also works fine if I change : => 2. But neither of these solutions gets me what I want.

    Any ideas on how I can achieve this?

    解决方案

    How about:

    interface
      real pure function f(y)
        real, dimension(:), intent(in) :: y
      end function
    end interface
    

    When you pass the argument of solve to the function, the size of the array will automatically be passed. You don't need to make this part of the interface.

    这篇关于将函数传递给子例程时,伪过程“f”中的接口不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆