【问题标题】:ocaml This expression has type 'a list but is here used with type X(account)ocaml 此表达式的类型为 'a list,但此处与类型 X(account) 一起使用
【发布时间】:2011-08-27 23:40:30
【问题描述】:

有一块 ocaml 可以正常工作

type position = {symbol: string; holding: int; pprice : float; };;
type account  = {name: string; max_ind_holding:float; pos:position list};;

let print_position pos = print_string "Holding: "; print_int pos.holding;
print_string ( " " ^ pos.symbol ^ "@" );
print_float pos.pprice;
print_newline(  );;


let print_account acct = print_string ( "Account_ID " ^ acct.name );
print_newline(  ); 
List.iter print_position acct.pos;;


(*MAIN PART OF CODE *)

let hashtbl_function db = 
    let hash_tbl_fold = Hashtbl.fold ( fun x y z -> ( ( y ) :: z ) ) db [] in
    ( fun x -> List.iter print_account x ) hash_tbl_fold (* THIS WORKS FINE *)
;;

但是,如果我想在这个函数(不在 print_account 中)中更改最后喜欢的“位置列表”的迭代,我会得到错误:

let hashtbl_function db = 
    let hash_tbl_fold = Hashtbl.fold ( fun x y z -> ( ( y ) :: z ) ) db [] in
    ( fun x -> List.iter print_position x ) hash_tbl_fold.pos (* Why this doesn't work ???*)
;;

错误:此表达式的类型为 'a list 但此处与类型帐户一起使用

但是 hash_tbl_fold.pos 是位置列表,这不是帐户类型。对吧?

在 print_account - acct.pos(获取'一个列表)是有效的,但在 hashtbl_function 中,hash_tbl_fold.pos -> 不是。

怎么可能,同一个表达式只适用于其中一个函数? 如何在 hashtbl_function 中迭代“位置列表”?

提前致谢!

【问题讨论】:

  • let ( db : ( string,account ) Hashtbl.t ) = Hashtbl.create 100;;

标签: functional-programming types function iterator ocaml


【解决方案1】:

好吧,我不确定你到底想做什么,但我可以告诉你为什么它不起作用。 hashtbl_fold 给你一个账户列表(输入account list)但是你正在做hashtbl_fold.pos;您无法获得列表的 pos 字段,因此会出现错误。

print_account 中,acct.pos 有效,因为acct 是单个帐户;不是帐户列表。

你想做什么?打印所有账户的所有头寸?还是只是单个(哪个?)帐户的头寸?

【讨论】:

    【解决方案2】:

    您的答案(这不是帐户,而是帐户列表类型)帮助我弄清楚。 现在,我可以在我的 hashtbl_function 中使用 hash_tbl_fold.pos。 这对我有用:

    let hash_tbl_fold =  Hashtbl.fold ( fun x y z -> ( ( y ) :: z ) ) db [] in
    List.iter ( fun x -> List.iter print_position x.pos ) hash_tbl_fold
    

    Tnx!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多