Hello everyone!
As my title says, I am want to merge two pattern matching functions into one function. The purpose of my goal is to create a function that converts: char list -> string.
So I made two functions:
let rec urejanje list = match list with
| [] -> []
| h::t -> Char.escaped h::urejanje t
let rec zdruzi list = match list with
| [] -> “”
| h::t -> h^zdruzi t
Now the first one’s input is char list ex.: [‘a’;‘b’;‘c’]. The first function converts char list into string list ex: [‘a’;‘b’;‘c’] -> [“a”;“b”;“c”]
Then the second function kicks in where input is result of first function: ex: [“a”;“b”;“c”]. The second function converts string list into string ex: [“a”;“b”;“c”] ->“abc”.
what I would like to do is somehow merge this two functions into one function.
I hope I made it clear what I want.
Regards
F
If only to satisfy the overall goal, then you can do
let f (l : char list) : string =
String.concat "" (List.map Char.escaped l)
If it must look like the original ones, then you can do
let f (l : char list) : string =
let rec aux (l : char list) (acc : string) : string =
match l with
| [] -> acc
| x :: xs -> aux xs (acc ^ (Char.escaped x))
in
aux l ""
Note that it might not be very efficient.
Thank you very much for reply!
what does it mean (l:char list) : string?
that input l is of type char list but what about that string then?
That’s just the function’s return type.
Ohh okay… so there is still just input l which is char list. got it! thank you very much!
But why do you have to declare that?
Best of regards
F
Just purely habit and personal preference.
I tend to do this just so I can spot the type immediately, which is quite important when you’re dealing with a lot of code.
Some people prefer only leaving type signatures in .mli files and so on.
Thank you very much for replying me. This lazy list looks long :S