[英]Put string in to list in Haskell
I need to create my own words functions. 我需要创建自己的文字功能。 It takes string and puts into list where ever there is space.
它接受字符串并将其放到有空间的列表中。 For example string "i need help" would result in ["i","need","help"].
例如,字符串“ i need help”将导致[“ i”,“ need”,“ help”]。 The definitions must be exactly
定义必须完全相同
anything :: String -> [String]
I currently came up with stupid solution which look like this ( also it doesn't work) 我目前想出了一个愚蠢的解决方案,看起来像这样(也是行不通的)
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)
test -> uses tail recursion 测试->使用尾递归
beforep -> get everything till first space 事前准备->将所有东西放到第一位
afterp -> gets everything after space afterp->在空格之后获取所有内容
Any ideas ? 有任何想法吗 ? If you have any other solutions to this problem it would help.
如果您对此问题有其他解决方案,则将有所帮助。 Thank you
谢谢
You've very nearly got it. 您已经快知道了。 If I attempt to run your code as is, I get:
如果我尝试按原样运行您的代码,则会得到:
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))'
So examine line 2: 因此,请检查第2行:
test d = beforep d : (test (afterp d)) : []
-- ^
-- This is the problem -----------------|
The type of the cons operator is: cons运算符的类型为:
(:) :: a -> [a] -> [a]
Your test
function returns a [String]
already, you don't want to try to cons it onto an empty list. 您的
test
函数已经返回了[String]
,您不想尝试将其限制在一个空列表中。 That would imply that the return type would be [[String]]
. 这意味着返回类型为
[[String]]
。
Try this instead: 尝试以下方法:
test d = beforep d : (test (afterp d))
After that change, it compiles, but when you run test "i need help"
you get the infinite list: 更改之后,它会编译,但是当您运行
test "i need help"
您将获得无限列表:
["i","need","help","","","","","","","",""...
The problem is that you need to include a base case in test
that stops when you pass it an empty list. 问题是您需要在
test
中包括一个基本案例,当您将其传递给空列表时,该案例将停止。 Here's the working code: 这是工作代码:
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.