简体   繁体   中英

Seq seq type as a member parameter in F#

why does not this code work?

type Test() =
  static member func (a: seq<'a seq>) = 5.

let a = [[4.]]
Test.func(a)

It gives following error:

The type 'float list list' is not compatible with the type 'seq<seq<'a>>'

Change your code to

type Test() = 
  static member func (a: seq<#seq<'a>>) = 5. 

let a = [[4.]] 
Test.func(a) 

The trick is in the type of a. You need to explicitly allow the outer seq to hold instances of seq<'a> and subtypes of seq<'a>. Using the # symbol enables this.

The error message describes the problem -- in F#, list<list<'a>> isn't compatible with seq<seq<'a>> .

The upcast function helps get around this, by making a into a list<seq<float>> , which is then compatible with seq<seq<float>> :

let a = [upcast [4.]]
Test.func(a)

Edit: You can make func more flexible in the types it accepts. The original accepts only sequences of seq<'a> . Even though list<'a> implements seq<'a> , the types aren't identical, and the compiler gives you an error.

However, you can modify func to accept sequences of any type, as long as that type implements seq<'a> , by writing the inner type as #seq :

type Test() =
  static member func (a: seq<#seq<'a>>) = 5.

let a = [[4.]]
Test.func(a) // works

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