简体   繁体   中英

OCaml- How to get tail of tuple list?

I'm a beginner to OCaml so I'm not sure if this is a right question. Anyway let's say I had a list of tuples [(1,2);(3,4);(5,6);(7,8);(9,10)]. I am pattern matching in a function so

let rec func list = match list with 
    |(* base case here *)
    |head1::head2::tail -> func head1::tail;; (* error here *)

Not real code, just to illustrate what I'm going to explain. When I use that pattern matching the first time, head1 is (1,2), head2 is (3,4), but tail seems to be only (5,6) instead of (5,6)(7,8)(9,10)...if I'm right. After all I'm getting "Error: This expression has type 'a * 'b but an expression was expected of type ('a * 'b) list" so I assume that must be what's happening. In the pattern matching how can I make tail be all of (5,6)(7,8)(9,10)?

It's not true that tail is just (5, 6) . tail is the full tail of the list as you expected.

To fix the problem you're describing, I think you just need parentheses around head1 :: tail .

In OCaml, function application has high precedence. So this expression:

func head1 :: tail

is parsed as if it were parenthesized like this:

(func head1) :: tail

but what you want (I think) is:

func (head1 :: tail)

I suspect there are other problems in the code, but this might get you going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM