【问题标题】:Using a stack inside a Haskell Function在 Haskell 函数中使用堆栈
【发布时间】:2013-02-25 21:58:57
【问题描述】:

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

  1. 取一个字符串
  2. 将此输入字符串的一些元素放入输出字符串,并将其他元素放入堆栈。
  3. 也将元素弹出到该输出字符串。
  4. 递归执行 2 和 3 直到堆栈为空。
  5. 堆栈为空时打印输出字符串。

我不知道何时何地创建该堆栈。由于我是 Haskell 编程的新手,所以我自己无法弄清楚。由于我还没有创建任何代码,我也无法显示任何代码。你能告诉我这个函数在算法上会是什么样子吗?我应该在哪里定义堆栈和输出字符串?谢谢。

【问题讨论】:

    标签: function haskell stack


    【解决方案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
    

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

    【讨论】:

    • 感谢您的回答。该函数最初应该只获取一个字符串。这符合您提供的结构吗?
    • 当您说“获取字符串”时,您的意思是从命令行吗?如果是这样,请将getLine 添加到domain 块中。
    • 我的意思是函数会像这样使用拥抱调用:function "stackoverflow"
    • 好的,但是堆栈从哪里来?它开始是空的吗?
    • 是的,它开始是空的,它必须在函数内部的某个地方创建,我不知道在哪里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2018-10-03
    • 2012-07-08
    • 1970-01-01
    • 2019-11-22
    • 2011-08-22
    • 1970-01-01
    相关资源
    最近更新 更多