1

我想知道如何用函数式编程语言做到这一点。也许是 F# 或 Haskell。

有人可以向我展示一个示例,而不使用除findand之外的任何函数调用rfind吗?

此函数使用(<0 表示向后)i的数量来查找下一个斜线。slash

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;
}
4

4 回答 4

13

哈斯克尔:

import Data.List

findSlash :: String -> Int -> Int
findSlash str i = findIndices (\c -> c == '\\' || c == '/') str !! i

处理负索引(这很丑,因为你真的不想这样做):

findSlash :: String -> Int -> Int
findSlash str i =
    index (findIndices (\c -> c == '\\' || c == '/') str) i
          where index xs i | i  < 0 = (reverse xs) !! ((-i) - 1)
                           | i >= 0 = xs !! i

处理错误:

findSlash :: String -> Int -> Maybe Int
findSlash str i = index i
    where xs = findIndices (\c -> c == '\\' || c == '/') str
          l = length xs
          index i
              | i <  0 && i < (-l) = Nothing
              | i >= 0 && i >= l   = Nothing
              | i <  0             = Just $ (reverse xs) !! ((-i) - 1)
              | i >= 0             = Just $ xs !! i

现在你可以说:

map (findSlash "/foo/bar/baz") [-4..4]

并得到:

-- -4        -3     -2     -1      0      1      2       3       4
[Nothing,Just 0,Just 4,Just 8,Just 0,Just 4,Just 8,Nothing,Nothing]

无论如何,处理最后的偏移量会使代码变得非常丑陋,并破坏了延迟评估的可能性。所以我认为大多数人会使用第一个,也许会加入一些错误检查。(这也会杀死懒惰,因为长度会强制评估整个列表。你可以使用“drop”而不是“!!”但是,为了避免错误并防止对整个结果列表进行评估。TMTOWTDI。)

于 2009-02-14T15:43:29.600 回答
7

首先,您的代码已损坏。size_t是无符号类型,永远不可能i<0

其次,您的代码是丑陋的标准库滥用和无效。应该使用正则表达式库等或使用手工扫描仪。生成的代码更干净、更快。例如(我已经很多年没有使用 C 语言了,但是下面的代码在 10 分钟内就可以工作了。):

size_t findSlash(const char *sz, int i)
{
    const char *s = sz;
    if (i<0) {
        for(;*s;s++);
        for(;;s--){
            if(s<sz) return -1;
            if((*s == '/') || (*s == '\\'))
                if(! ++i) break;
        }
    }
    else {
        for(;;s++){
            if(! *s) return -1;
            if((*s == '/') || (*s == '\\'))
                if(! i--) break;
        }
    }
    return s-sz;
}

我没有写过 Haskell 或 F#,但是例如下面的 Erlang 代码应该说明如何用函数式语言来做:

findslash(L, I) when is_list(L), is_integer(I) ->
    if  I<0  ->
            case findslash(lists:reverse(L), -1*I - 1, 0) of
                none -> none;
                X -> length(L) - X - 1
            end;
        I>=0  -> findslash(L, I, 0)
    end.

findslash([H|_], 0, X) when H=:=$/; H=:=$\\ -> X;
findslash([H|T], I, X) when H=:=$/; H=:=$\\ ->
    findslash(T, I-1, X+1);
findslash([_|T], I, X) -> findslash(T, I, X+1);
findslash([], _, _) -> none.

我在 Haskell 中尝试进行错误检查并保持 i>=0 的惰性:

findSlash :: String -> Int -> Maybe Int
findSlash str i
  | i <  0 = reversed (_findSlash (reverse str) (-1*i-1) 0)
  | i >= 0 = _findSlash str i 0
    where
      reversed Nothing  = Nothing
      reversed (Just a) = Just ((length str) - a - 1)
      _findSlash (x:xs) i n
        | x == '/' || x == '\\' = if i==0 then Just n else _findSlash xs (i-1) (n+1)
        | True                  =                          _findSlash xs  i    (n+1)
      _findSlash []     _ _     = Nothing
于 2009-02-14T15:27:15.973 回答
4

您可以用纯 C 编写纯功能代码:

/** Return pointer to the `n`-th occurrence of any char from `chars` in `s`.

    Return NULL if it can't find the `n`-th occurrence.  
    Start at the end of `s` if `n` is negative.
    `n` is zero-based.
*/
const char* 
find_nth(const char* s, int n, const char* chars) 
{
  if (n < 0) return rfind_nth(s, -(n+1), chars);
  if (! (s && *s)) return NULL;
  if (find(chars, *s)) return (n == 0) ? s : find_nth(s+1, n-1, chars);
  else return find_nth(s+1, n, chars);
}

完整程序:

#include <string.h>

const char* 
find(const char* s, char c) 
{
  if (! (s && *s)) return NULL;
  return (*s == c) ? s : find(s + 1, c);
}

const char* 
rfind_nth_range(const char* s, const char* end, size_t n, const char* chars)
{
  if (! (s && end && (end - s) > 0)) return NULL;
  if (find(chars, *(end - 1))) // `*(end-1)` is in `chars`
    return (n == 0) ? end - 1 : rfind_nth_range(s, end - 1, n-1, chars);
  else
    return rfind_nth_range(s, end - 1, n, chars);
}

const char* 
rfind_nth(const char* s, size_t n, const char* chars)
{
  return rfind_nth_range(s, s + strlen(s), n, chars);
}

int 
main(void) 
{
  const char* const s = "ab/cd\\e";
  return !(find_nth(s, 1, "/\\") == (s+5));
}
于 2009-02-15T01:55:57.880 回答
3

那么,呃,这是什么?它是否只在字符串中找到第 i 个斜杠(向前或向后)(如果 i 为负数,则从末尾开始第 i 个)?我不确定我是否只是通过阅读代码来正确解释它。

无论如何,移植都很简单,但尚不清楚您的目标/目的是什么。

于 2009-02-14T06:10:45.153 回答