0

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"]. 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

Any ideas ? If you have any other solutions to this problem it would help. Thank you

4

1 回答 1

5

你已经很接近了。如果我尝试按原样运行您的代码,我会得到:

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函数已经返回 a [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.
于 2013-10-29T14:11:50.167 回答