Haskell,在一个函数中执行一些代码,然后是 if 语句

Haskell, doing some code followed by an if statement in one function

我已经使用 haskell 大约一个星期了,我似乎不明白如何在每次调用函数时执行的 if 语句上方添加一行代码。以下是我为解决这个问题而整理的代码:

let example x = 
    if (x == 1) then "Number is 1" 
    else if (even x) then example (x - 1) 
    else example (x - 2) 

我想要发生的是每次调用函数时打印数字,所以逻辑告诉我找出如何在 if 语句上方添加一行来打印 [x]。我已经深入研究了它,但未能找到解决方案。我查看了 "Do" 但我似乎无法让它工作。如果有人能在这个领域发光,将不胜感激。

您需要 return 一个 IO () 并且您可以使用 do 符号,例如

example :: Int -> IO ()
example x = do
  putStrLn $ "Number is " ++ (show x)
  case x of
    1 -> return ()
    _ -> if (even x) then example (x-1) else example(x-2)

如果你要在屏幕上打印一些东西,你的函数必须是一个 IO 动作,所以首先它需要一个类型签名来表明这一点。接下来,要在您的函数中执行一系列 IO 操作,您应该使用 do 语法,但这意味着要从中 return 一个值,您需要使用 return 函数:

example :: Int -> IO String
example x = do
    putStrLn $ "Calling: example " ++ show x
    if x == 1
        then return "Number is 1"
        else if even x
            then example (x - 1)
            else example (x - 2)

您不需要 example (x - 1)example (x - 2) 上的 return 因为这些表达式的类型是 IO String,它已经是 [= 所需的类型27=] 这个函数的值。但是,"Number is 1" 的类型只有 String。要将其变为 IO String,您必须使用 return 函数。

看看 trace 函数。它专门满足您的需求。并且不需要更改函数的签名。

import Debug.Trace

example x = trace ("Called with " ++ (show x)) $
    if (x == 1) then "Number is 1" 
    else if (even x) then example (x - 1) 
    else example (x - 2) 

Documentation 对于 trace