Search code examples
stringfilef#option-type

How to merge string options to a single string option in fsharp?


this is my homework :) Hope someone can help!

How do i merge 2 string options into a single string option in fsharp? It has to be in the connect function, and right now my code looks like this:

open System.IO

let getFile (name : string) : string option = 
    if File.Exists(name) then
       Some (File.ReadAllText name)
    else
       None 

let connect (name : string list) : string option = 
    getFile name.[0]

So the output of connect function should be contents of A.txt + B.txt as a single string. If one of the files doesn't exist it should return None. I'm interested in how do I merge the content of first element in list together with the second? I have tried + and option.bind but can't get It to work.
Thanks in advance


Solution

  • Something like this:

    let string1 = Some "Hello "
    let string2 = Some "World"
    
    Option.map2 (+) string1 string2