Jack
Jack

Reputation: 415

Get position of first and last char in substring

I would like to make a function in OCaml that return the position of the first and last char in a substring. For example my_sub "tar" "ar" will return (1,2) but if I have my_sub "tabr" "ar" it will be Nil, it must be consecutive. How can I do that ?

Edit

I tried to make the code but I have a problem

let rec pos_sub l t n =
  let rec aux l1 l2 x =
    match l1, l2 with
    | [], _ | _, [] | [], [] -> -1
    | h1::q1, h2 | h1, h2 -> if h1 = h2 then x else -1
    | h1::q1, h2::q2 -> if h1 = h2 then aux q1 q2 x+1 else -1
  in
  match l, t with
  | [], _ -> (-1,-1)
  | h1::q1, h2::q2 -> if h1 = h2 then (n, (aux q1 q2 n+1)) else pos_sub q1 t n+1

it says :

The variable h1 on the left-hand side of this or-pattern has type 'a but on the right-hand side it has type 'a list The type variable 'a occurs inside 'a list

in the second match in aux

Upvotes: 0

Views: 838

Answers (1)

mschmidt
mschmidt

Reputation: 2790

Your problem in the code is, that in this match:

| h1::q1, h2 | h1, h2 -> if h1 = h2 then x else -1

you try to compare a single character h1 with h2 which is of type string. This is what the error message tries to tell you. I think you intended match the case, where h2 is the last character of your search string, therefore:

| h1::q1, h2:[] | h1:[], h2:[] -> if h1 = h2 then x else -1

and because q1 is unused, this can then be simplified to:

| h1::_, h2:[] -> if h1 = h2 then x else -1

A sidenode: it is bad style to use -1 or similar as special values to signal error cases. Rather use optional types in such situations.

Upvotes: 1

Related Questions