繁体   English   中英

将字符串放入Haskell中的列表

[英]Put string in to list in Haskell

我需要创建自己的文字功能。 它接受字符串并将其放到有空间的列表中。 例如,字符串“ i need help”将导致[“ i”,“ need”,“ help”]。 定义必须完全相同

anything :: String -> [String]

我目前想出了一个愚蠢的解决方案,看起来像这样(也是行不通的)

test :: String -> [String]
test d = beforep d : (test (afterp d)) : []

beforep :: String -> String
beforep d = takeWhile (/=' ') d
afterp :: String -> String
afterp d = if (dropWhile (/=' ') d)==[] then []
      else tail(dropWhile (/=' ') d)

测试->使用尾递归

事前准备->将所有东西放到第一位

afterp->在空格之后获取所有内容

有任何想法吗 ? 如果您对此问题有其他解决方案,则将有所帮助。 谢谢

您已经快知道了。 如果我尝试按原样运行您的代码,则会得到:

test.hs:2:23:
    Couldn't match expected type `Char' with actual type `String'
    Expected type: String
      Actual type: [String]
    In the return type of a call of `test'
    In the first argument of `(:)', namely `(test (afterp d))'

因此,请检查第2行:

test d = beforep d : (test (afterp d)) : []
--                                      ^
-- This is the problem -----------------|

cons运算符的类型为:

(:) :: a -> [a] -> [a]

您的test函数已经返回了[String] ,您不想尝试将其限制在一个空列表中。 这意味着返回类型为[[String]]

尝试以下方法:

test d = beforep d : (test (afterp d))

更改之后,它会编译,但是当您运行test "i need help"您将获得无限列表:

["i","need","help","","","","","","","",""...

问题是您需要在test中包括一个基本案例,当您将其传递给空列表时,该案例将停止。 这是工作代码:

test :: String -> [String]
test [] = []
test d = beforep d : (test (afterp d))

beforep :: String -> String
beforep d = takeWhile (/=' ') d

afterp :: String -> String
afterp d = if (dropWhile (/=' ') d)==[]     -- Slightly reformatted
             then []                        -- to improve readability,
             else tail(dropWhile (/=' ') d) -- no real change.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM