简体   繁体   中英

Recursive functions for sequences in F#

Rather trivial question, but a quick google search didn't give me the answer.

What is a standard way to write a recursive functions for sequences? For lists you would do pattern matching with empty list and head+tail pattern, what is the equivalent for sequences?

There is no standard way to do so since you rarely write recursive functions for sequences.

You should look at a variety of high-order functions in Seq module . They are often more than adequate, so you don't have to write recursive functions by yourself.

To generate sequences recursively, sequence expression is a simple and intuitive way to go:

let rec allFiles dir =
    seq { yield! Directory.GetFiles dir
          for d in Directory.GetDirectories dir do
            yield! allFiles d }

If you have to break down a sequence and manipulate it recursively, you are doing it wrong. You should either manipulate List or LazyList from F# PowerPack , and convert results back to sequences.

There is no way to get the tail of a sequence because it has not been evaluated (and could in theory be infinite), so you cannot pass the tail into a function recursively. You would just use Seq.iter or yield! to go through the sequence.

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