0

I've constructed a mutual-recursive type, consisting of more primitive types also defined like follows:

type Title = Title of string;;
type Value = Value of int;;

type Subcol = Collection list
and Collection = 
    | Col of Title * Value * Subcol
    ;;

The subcol may or may not be the empty list, but if it isn't, I'd like to sum both the value of the given collection as well as recursive call on Subcol and the Value defs it might contain. To do this I've constructed the following function:

let rec colList = function
    | []          -> 0
    | _::v::s     -> (colList s) + sumVal v
and sumVal = function
    | Value v        -> v
and col = function
    | Col(_,v,[]) -> (sumVal v)
    | Col(_,v,s)  -> (sumVal v) + (colList s)
    ;;

I expect the function call colList s in

Col(_,i,s)  -> (sumVal i) + (colList s)

to produce an int from a Subcol type, however I get the following error:

error FS0001: Type mismatch. Expecting a Value list but given a Subcol The type 'Value' does not match the type 'Collection'

I want the colList to accept Subcols, not Value lists.

Any help is appreciated, thank you.

Syncretic
  • 75
  • 10
  • 2
    seems you want `col v` here instead of `sumVal v`: `| _::v::s -> (colList s) + col v` - note that you can easily circumvent those nasty searches if you provide type annotations ;) – Random Dev Oct 29 '15 at 18:34
  • Thank you very much for the correction: that is indeed what I wanted. But even more importantly thank you for the tip about annotations, I can definitely see the uses of keeping good practice :) – Syncretic Oct 29 '15 at 19:55
  • Are you looking for more of an answer than you already got? It appears this is a simple logic error. – N_A Oct 29 '15 at 23:10
  • Maybe I missed something but why the mutual recursive function where a `fold` (or better a `sumBy`) can do the job ? It won't be tail-rec but the actual code isn't too : `let rec colList subs = List.fold (fun acc (Col (_, Value v, subs)) -> acc + v + colList subs) 0 subs` *(Note I choose to not do eta-conversion to avoid the recursive value warning)* – Sehnsucht Oct 29 '15 at 23:15

0 Answers0