문제

I understand that F# functions return a unit if nothing else is returned, but this function returns a string. Can someone please help me understand why it returns a unit?

let rec processList aList str = 
    match aList with
    | h::t  ->  let x = Regex.Replace(str, h, h, RegexOptions.IgnoreCase)
                processList t x
    | []    ->  printfn "%s" str
도움이 되었습니까?

해결책

The stopping case for this recursive function | [] -> printfn "%s" str

returns unit, and therefore the function returns a unit. The other branch only recursively call the same function.

다른 팁

If we analyse the two recursive branches, their return types must be identical.

The first branch has some return type 'a which is the return value of processList

The second branch returns unit as that is the return type of printfn. You probably want to have just

| [] -> str

or for a more complex case, you can use sprintf to return a formatted string as follows

| [] -> sprintfn "%s" str
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top