2013-03-10 141 views
1

我想在Haskell函数中使用堆栈,但我不知道如何使用它。我的功能应该是这样工作的:在Haskell函数中使用堆栈

  1. 一个字符串
  2. 将这个输入字符串输出字符串的一些元素,并把他人叠加。
  3. 将元素也弹出到该输出字符串。
  4. 做2和3递归,直到栈是空的。
  5. 当堆栈为空时打印输出字符串。

我不知道何时何地创建该堆栈。由于我在Haskell编程方面很新,所以我无法自己弄清楚。由于我没有创建任何代码,我也无法显示任何代码。你能以算法的方式告诉我函数的外观吗?我应该在哪里定义堆栈和输出字符串?谢谢。

回答

1

这里的一个舒适的事情是,标准的Haskell列表是一个很好的堆栈(自然,记住堆栈是一个更受限制的列表)。你的功能可能看起来像这样:

--takes one string and uses a stack to convert it to another string 
doSomethingWithStack :: String -> [String] -> String 
doSomethingWithStack str stack = 
    let str' = --here you embody your points 2 and 3 
     stack' = --stack top is (head stack), push is (x : stack), pop is (tail stack) 
     --... any change you'd want to make to any value turns into a new variable 
    in case stack'' of --check the final variables 
      [] -> str'' --if stack is empty, end 
      _ -> doSomethingWithStack str'' stack'' --if not, repeat 

--now, to make it pretty 
fancyWrapper :: String -> String 
fancyWrapper str = doSomethingWithStack str [] -- empty list is an empty stack 

--because you should strive to separate pure and impure functions 
--, I suggest that you do the print elsewhere, say 
main = do 
     str <- getLine 
     print $ fancyWrapper str 

希望这既不是太少,也不是太多。一旦遇到问题,请尝试并询问更具体的问题。

+0

感谢您的回答。该函数应该首先得到一个字符串。这是否符合你提供的结构? – jason 2013-03-10 20:57:48

+0

当你说“得到一个字符串”,你的意思是从命令行?如果是这样,在'main'的'do'块中添加'getLine'。 – 2013-03-10 21:55:17

+0

我的意思是功能将被称为像这样使用拥抱: 函数“stackoverflow” – jason 2013-03-10 22:02:52