指定多态函数的类型以将其作为参数传递 [英] Specify type of polymorphic function to pass it as argument

查看:75
本文介绍了指定多态函数的类型以将其作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数curry,该函数将函数(A, B) -> C作为参数,并返回A -> B -> C.它在功能g(a: Int, b: Int) -> Int上正常工作.另外,我有一个函数f,它是多态的,所以它的类型是模棱两可的.这是代码:

I have function curry that takes a function (A, B) -> C as an argument, and returns A -> B -> C. It works fine on function g(a: Int, b: Int) -> Int. Also, I have function f, that is polymorphic, so its type is ambigous. Here is the code:

func g(a: Int, b: Int) -> Int { return a + b }

func f(a: Int, b: Int) -> Int { return a + b }
func f(a: Float, b: Float) -> Float { return a + b }

func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
  return { a in { b in f(a, b) } }
}

let curriedG = curry(g) //curriedG type Int -> Int -> Int

let curriedF = curry(f) //Error, Ambigous use of 'f(_:b:)'

很明显,我不能执行curry(f),但是有什么办法,所以我可以指定要使用特定的f()实现?

It is obvious, that I can't do curry(f), but, is there any way, so I could specify, that I want to use specific f() implementation?

我为什么需要这个. 由于初始化器.我想咖喱特定的初始化程序,假设struct A有两个初始化程序:init(t: T, y: Y)init(u: U, h: H),我想咖喱其中之一.

Why I need this. Because of initialisers. I want to curry specific initialiser, lets say struct A has two initialisers: init(t: T, y: Y) and init(u: U, h: H), I want to curry one of them.

谢谢!

推荐答案

由于f超载,您必须指定要使用的f:

Since f is overloaded, you have to specify which f you want:

let curriedF = curry(f as (Float, Float) -> Float)

或结果应该是什么:

let curriedF = curry(f) as Float -> Float -> Float

这篇关于指定多态函数的类型以将其作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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