如何使用递归函数从文本到第一个空格获取字符串?

Dod*_*nde 3 string recursion haskell

在我的作业中,我的任务是编写一个递归函数,该函数将返回文本的第一个单词,""如果第一个字符是空格,则返回该单词。

这是我的功能:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeword (x:xs) 
    | x == ' ' = []
    | otherwise = x : takeword xs
Run Code Online (Sandbox Code Playgroud)

它应该像这样工作:

takeWord " one"    = ""
takeWord "one two" = "one"
takeWord ""        = ""    --returns with "Non-exhaustive patterns in function takeword"
takeWord "one"     = "one" --and this too
Run Code Online (Sandbox Code Playgroud)

但是在没有空间的情况下,它将返回以下错误消息:

函数序言中的非穷尽模式

正确的代码是什么?

Wil*_*sem 6

您在此处定义了两个函数:大写和小写。前者仅适用于空列表,后者仅适用于非空列表。takeWordWtakewordw

因此,您应该选择两个名称之一,例如:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeWord (x:xs) 
    | x == ' ' = []
    | otherwise = x : takeWord xs
Run Code Online (Sandbox Code Playgroud)

我们可以通过匹配模式中的空格而不是后卫中的空格来使其更加优雅:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeWord (' ':_) = ""
takeWord (x:xs) = x : takeWord xs
Run Code Online (Sandbox Code Playgroud)

请注意,您可以在takeWhile :: (a -> Bool) -> [a] -> [a]这里使用:

takeWord :: [Char] -> [Char]
takeWord = takeWhile (' ' /=)
Run Code Online (Sandbox Code Playgroud)