开发者

ocaml This expression has type 'a list but is here used with type X(account)

there is piece of ocaml which works correctly

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 *)
;;

But, if i want to change last like to do iteration of 'position list' in this function (not in pri开发者_开发百科nt_account), i will got error :

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 ???*)
;;

Error: This expression has type 'a list but is here used with type account

But hash_tbl_fold.pos is list of position, this is not account type. Right?

In print_account - acct.pos (to get 'a list) is work, but in hashtbl_function, hash_tbl_fold.pos -> not.

How it can be, that the same expression only works in one of the functions ? How i can iterate 'position list' in hashtbl_function?

thanks in advance!


Well, I'm not sure what exactly you want to do but I can tell you why it doesn't work. hashtbl_fold gives you a list of accounts (type account list) but then you are doing hashtbl_fold.pos; you cannot get a pos field of a list, hence the error.

In print_account, acct.pos works because acct is a single account; not a list of accounts.

What do you want to do? Print all positions of all accounts? Or just positions of a single (which?) account?


Your answer (this is not account, but account list type) help me to figure it out. Now, i can use hash_tbl_fold.pos inside my hashtbl_function. This works for me:

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜