1

I am trying to write a function that takes the characters x, r, c and returns r if x = c, or returns x if x != c. It basically replaces a matching character with another, or returns the original one if not.

I tried implementing this using pattern matching, but it doesn't behave the way i thought it would. My goal is to transform the string "hello" to the string "herro":

let swap_id c r x =
    match x with
    | c -> r
    | _ -> x

let swap_id_2 x =
    match x with
    | 'l' -> 'r'
    | _ -> x

// prints "rrrrr"
printfn "%s" ("hello" |> String.map (swap_id 'l' 'r'))

// prints "herro"
printfn "%s" ("hello" |> String.map (swap_id_2))

My Intellisense also tells me, that the _ pattern is never matched in my first function.

How are these two different? What am i missing?


Note: I know there is a string.replace(..) function. I just wanted to implement my own one to learn something.

Luca Fülbier
  • 2,641
  • 1
  • 26
  • 43

0 Answers0