有没有在另一函数内调用函数的特定方法?

时间:2019-03-30 13:06:49

标签: haskell

我正在设置一个递归函数,该函数调用另一个函数以将值从一个字符串转移到另一个字符串。我可以在函数left中使用所有功能,但是我一直在努力理解如何递归调用left函数的语法。

该函数应在检测到值" "中的空格(a)时停止。

left :: (String, String) -> (String, String) 
left (a, b) = (reverse(tail(reverse a)), ((head(reverse a))) :b)

reu' :: (String, String) -> (String, String)
reu' (a, b)
    | a ==  " " = (a, b)
    reu'(a, b) = left (a, b)

输入:"This is an ex""ample of a string"

预期:"This is an""example of a string"

1 个答案:

答案 0 :(得分:0)

由于您需要分析a end ,因此递归会有些麻烦。我可能会使用预定义的initlast函数来简化操作,并使用单词而不是单个字符。请注意,这将代替对left的需求。

reu' (String, String) -> (String, String)
reu' a b = let w = words a  -- ["This", "is", "an", "ex"]
               a' = init w  -- ["This", "is", "an']
           in (unwords a', last w : b)

如果您想自己进行递归,则反转a 一次并将字符从该字符串的 front 移到b,然后在找到空白后重新反转剩余的内容。

reu' (String, String) -> (String, String)
reu' a b = reu'' (reverse a) b  -- reu'' "xe si na sihT" "ample of a string"
     where reu'' "" ys = ("", ys)
           reu'' (' ':xs) ys = (reverse xs, ys)
           reu'' (x:xs) ys = reu'' xs (x:ys)