【发布时间】:2014-02-12 19:45:47
【问题描述】:
我目前正在尝试使用 Ocaml 构建一个 hopfield 网络。我无法制作一些函数来让这一切正常工作,并且不知道如何完成它们。
第一个是能量函数。
这是我的功能:
let rec energy(state, weightMatrix) =
if weightMatrix == [] then 0.0
else
(hd(state) *. hd(weightMatrix))/2.0 +. energy(tl(state),tl(weightMatrix));;
state 是它所处的状态,而 weightMatrix 是权重矩阵。它遵循等式:
这方面的一个例子是:
state = = [1.0; -1.0; 1.0; -1.0] and
weight = [[0.; -1.; 1.; -1.]; [-1.; 0.; -1.; 1.];[1.; -1.; 0.; -1.];[-1.; 1.; -1.; 0.]]
# energy(state,weight);;
- : float = -6.
当我运行我的函数时,我在函数的最后一行收到以下错误:
Error: This expression has type float but an expression was expected of type
int
编辑:修复上述错误后,我现在遇到了这个错误:
Error: This expression has type float list list
but an expression was expected of type float list
Type float list is not compatible with type float
我认为我的问题可以从这里看出:
I am getting: val energy : float list * float list -> float = <fun>
but want: val energy : float list * float list list -> float = <fun>
还有,
我必须创建两个函数来进入网络中的下一个状态,但我无法从逻辑上思考如何完成。我的功能大纲是:
let nextState(currentState, weightMatrix, alpha) =
;;
如果有人能帮我解决这个问题,那就太好了!
【问题讨论】:
-
一些事情,1) 通常你不会像在 C 中那样调用函数。
,生成元组。您可以用空格分隔参数。 2) 通常 OCaml'ers 直接使用模式匹配而不是 hd/tl。 3)添加类型注释有助于调试。在函数参数上使用(state : weightMatrix list list)之类的东西。您会看到您实际上使用的是权重矩阵,就好像它是float list。 4) 这些函数似乎更适合数组。 -
@nlucaroni 谢谢!我在哪里像在 C 中一样调用?那么我将如何使用 weightMatrix 作为浮动列表?
-
函数
let rec energy(state, weightMatrix) =在 OCaml 中将是let rec energy state weightmatrix =。 -
@nlucaroni 哦,是的,这是有道理的!我没有意识到这一点。另外,您能否举一个例子说明我如何不将 weightMatrix 设为浮动列表?
-
(hd(state) *. hd(weightMatrix))。因为hd(weightmatrix)是一个浮点数(因为您将它与hd(state)相乘),并且 hd 对列表进行操作,所以 weightmatrix 被推断为一个浮点数列表。