对于以下代码,
func :: Show a => a -> a
func = id
func3 = func . func
Run Code Online (Sandbox Code Playgroud)
编译抱怨消息
Ambiguous type variable `c0' in the constraint:
(Show c0) arising from a use of `func'
Possible cause: the monomorphism restriction applied to the following:
func3 :: c0 -> c0 (bound at test.hs:6:1)
Probable fix: give these definition(s) an explicit type signature
or use -XNoMonomorphismRestriction.
Run Code Online (Sandbox Code Playgroud)
但是,在GHCi中查询其类型可以正常工作.
*Main> :t func . func
func . func :: Show c => c -> c
Run Code Online (Sandbox Code Playgroud)
这里发生了什么事?有没有办法让func3 …
给出A带有数据类型的签名t,比方说
signature A = sig
datatype t = T of int | S of string
end
Run Code Online (Sandbox Code Playgroud)
是否有可能提供一个没有t重复的实现(结构)?例如,在以下签名中,t重复定义.它适用于小型数据类型,但对于较大的数据类型则有点笨拙.
structure AImpl : A = struct
datatype t = T of int | S of string
end
Run Code Online (Sandbox Code Playgroud)
我的目的只是提供一个接口,以便人们可以知道所有的声明.但我不希望每个实现都重复数据类型定义.
虽然签名和结构似乎都可以包含来自另一个结构的数据类型,但是通过单独检查签名,人们就无法知道数据类型声明.例如:
structure AData = struct
datatype t = T of int | S of string
end
signature A = sig
datatype t = datatype AData.t
end
structure a : A = struct
open AData
end
Run Code Online (Sandbox Code Playgroud)
当然,这种方法,虽然不是很有满足感,是可以接受的,如果我把两者AData …
什么是联合类型和交集类型?
我已经咨询了这个问题,但是一些小型工作类型系统会更好,而不是必要的实用系统.
具体来说,通过联合类型,我指的是本博文中提到的 而不是sum类型,其中伪代码看起来像
{String, null} findName1() {
if (...) {
return "okay";
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在维基百科页面有交集类型与联合类型的简短说明,但似乎这个没有进一步的参考.
我编写了以下代码,它使用类型的函数function<int(int)>.的功能compose,print,inc和guarded是其结合其他功能或产生一些外部作用助手.然后我用它们来构建我的程序:
/* start of the program */
function<int(int)> recursion();
function<int(int)> go =
compose(guarded(10, recursion()), compose(inc, print("go")));
function<int(int)> recursion() {
return compose(go, print("recursion"));
}
Run Code Online (Sandbox Code Playgroud)
然而,打电话时recursion()(0),一个异常std::bad_function_call被抛出时go达到第二时间,但我不明白为什么.有悬挂参考还是空的std::function?此外,eta扩展go工作:
function<int(int)> go = [](int n) -> int {
return compose(guarded(10, recursion()), compose(inc, print("go")))(n);
};
Run Code Online (Sandbox Code Playgroud)
原始代码有什么问题?为什么替代方案有效?
完整代码:
#include <string>
#include <iostream>
#include <functional>
using namespace std;
/* helper functions, some combinators */
//composing two functions, f1 . …Run Code Online (Sandbox Code Playgroud)