Search code examples
f#closuressequenceyield

How to (is it possible to) call yield inside of closure in F#?


I am trying to write a function, which takes sequence of strings and returns the sequence of strings all prefixed by given another string with the help of Seq.iter, but can't deduce correct syntax.

//let concatElemSeq (elem : string) (s : seq<string>) : seq<string> = (Seq.map (fun it -> elem+it) s)

let concatElemSeq (elem : string) (s : seq<string>) : seq<string> = seq {
    Seq.iter (fun it -> 
        yield elem+it
        ()
    ) s
}

How to accomplish?


Solution

  • No, it is not possible to nest yield like that. yield has to be part of the computation expression syntax.

    To achieve what you want, use for:

    let concatElemSeq (elem : string) (s : seq<string>) : seq<string> = seq { 
        for it in s do
            yield elem+it
    }
    

    Or even shorter, using -> as a shortcut for do yield:

    let concatElemSeq (elem : string) (s : seq<string>) : seq<string> = seq { 
        for it in s -> elem+it
    }
    

    Alternatively, you can do this with Seq.map and partially applied (+):

    let concatElemSeq elem s = Seq.map ((+) elem) s
    

    And then eta-reduce:

    let concatElemSeq elem = Seq.map ((+) elem)