I am wondering how to do this in a functional programming language. Maybe F# or Haskell.
Can someone show me an example without using any function calls except for find and rfind?
This function finds the next slash using i as the num of slash (<0 for backwards).
size_t findSlash(const char *sz, size_t i) { std::string s = sz; size_t a, b, c, n, ai = abs(i), pos=0; for (n=0; n<ai; n++) { if (i<0) { a = s.rfind('\\', pos); b = s.rfind('/', pos); } else { a = s.find('\\', pos); b = s.find('/', pos); } if (a==-1u) { if (b==-1u) return pos; c = b; } else if (b==-1u) c = a; else c = min(a, b); pos = c+1; } return c; }
In first, your code is broken.
size_tis unsigned type and never can bei<0.In second, your code is ugly std library misuse and ineffective. There should be used regular expression library or such or use handcrafted scanner. Resulting code is far cleaner and faster. For example (I have not been using C for many years but below code crafted in 10 minutes works.):
I haven’t used to write Haskell or F# but for example below code in Erlang should state as example how to do it in functional language:
My attempt in Haskell with error checking and keeps laziness for i>=0: