我正在使用 OCaml 中的地图模块。考虑以下代码来创建一个以整数为键的映射:
module Int = struct
type t = int
let compare a b = a - b
end
module IntMap = Map.Make(Int)
let m = IntMap.(empty |> add 3 "hello")
Run Code Online (Sandbox Code Playgroud)
这一切都很好。它的编译和行为符合我的预期。
但是,如果我为模块添加类型注释,Int那么顶行将变为:
module Int : Map.OrderedType = struct
Run Code Online (Sandbox Code Playgroud)
最后一行导致编译错误:
let m = IntMap.(empty |> add 3 "hello")
^
Error: This expression has type int but an expression was expected of type
IntMap.key = Int.t
Run Code Online (Sandbox Code Playgroud)
然而IntMap.key和Int.t都只是 的别名int。此外,该Int模块的类型为Map.OrderedType。我知道这一点是因为这是 …
我对 f# 编程相当陌生,虽然我非常喜欢它,但困扰我的一件事是,在 f# 中以感觉“正确”的方式编写代码经常会导致速度极其缓慢。我一直在使用 f# 开发神经网络,与其他语言的实现相比,我的代码速度非常慢。一种具体情况是以下线性代数函数:
// Dot Product
// Slow
let rec dotProduct (vector1 : float []) (vector2 : float []) : float =
if vector1 |> Array.length = 0 then
0.0
else
vector1.[0] * vector2.[0] + (dotProduct (vector1 |> Array.tail) (vector2 |> Array.tail))
// Fast
let dotProduct (vector1 : float []) (vector2 : float []) =
Array.fold2 (fun state x y -> state + x * y) 0.0 vector1 vector2
Run Code Online (Sandbox Code Playgroud)
// Matrix Vector Product
// Slow
let …Run Code Online (Sandbox Code Playgroud)