Haskell技术问题:如何传递函数结果至另一函数并复用
Hey there, fellow Haskell newbie! Let's break down your questions step by step—this stuff clicks once you get the hang of it, I promise.
In Haskell, this ties directly into the language's functional core, and there are a few straightforward ways to do it:
Direct nested calls: For pure functions (no side effects), you can wrap the first function call inside the second. Example:
-- Sample helper functions double :: Int -> Int double x = x * 2 increment :: Int -> Int increment x = x + 1 -- Pass increment's result directly to double finalValue :: Int finalValue = double (increment 3) -- Results in (3+1)*2 = 8Function composition: For cleaner chaining (especially with multiple functions), use the
.operator. This reads as "apply increment first, then double":finalValue :: Int finalValue = (double . increment) 3 -- Same result as aboveIn IO contexts (like user input): When working with side effects, use a
doblock to bind the result to a variable, then pass that variable to other functions. We'll see this in action with your second question!
Let's build a complete, working example for your test.hs file that meets your requirements:
import Data.Char (isDigit) main :: IO () main = do putStrLn "Please enter an 8-10 digit number string:" userInput <- getLine -- Validate input first (must be 8-10 digits only) if length userInput >= 8 && length userInput <= 10 && all isDigit userInput then do -- Remove last character with `init` (safe here since input is non-empty and long enough) let trimmedInput = init userInput putStrLn $ "Trimmed result: " ++ trimmedInput -- Reuse trimmedInput for follow-up operations! -- Example 1: Pass to a custom processing function let processed = addIdentifier trimmedInput putStrLn $ "Processed value: " ++ processed -- Example 2: Use in another IO action putStrLn $ "Reversed trimmed value: " ++ reverse trimmedInput else putStrLn "Oops! Please enter a valid 8-10 digit string (no letters or symbols)." -- Example helper function to demonstrate reuse addIdentifier :: String -> String addIdentifier s = "PROCESSED_" ++ s
Key details:
getLinereads user input, and<-binds that input touserInput(this is how you capture results from IO actions).initsafely removes the last character of a non-empty string—we’ve already validated the input length, so no risk of errors here.- Once
trimmedInputis bound withlet, you can reuse it anywhere in thethenblock: pass it to helper functions, print it multiple times, or use it as input for other IO tasks.
To run this, load test.hs in GHCi via cmd (ghci test.hs), then call main—you’ll see the trimmed value get reused exactly as you need.
内容的提问来源于stack exchange,提问作者cars

