The Haskell core: one pure function and one loop
The core is two files and about fifty lines. One is the logic and has no IO in it at all: respond :: String -> String takes the request line and returns the answer line. The other is the shell around it: a loop that reads a line, prints the answer and reads again.
That split is the reason the rest of the set is short. A pure function can be tested by calling it, which is what the test page does from Python; the same function is what the shared library exports, so the ctypes page has no second implementation to keep in step; and the executable is the only thing that knows about standard input.
A pure function from line to line
The price list is an association list and the lookup is lookup from the Prelude, which is a linear search over three entries. The quantity is read by a total function: three guards reject an empty field, a field longer than three characters and a field with a non-digit, and the value is checked against the bottom of the range.
module Pricing (respond) where
import Data.Char (isDigit)
import Text.Printf (printf)
prices :: [(String, Int)]
prices = [("tea", 250), ("coffee", 975), ("cake", 400)]
respond :: String -> String
respond line =
case words line of
["PRICE", sku, quantity] ->
case (lookup sku prices, readQuantity quantity) of
(Nothing, _) -> failure "E_SKU" ("unknown sku: " ++ sku)
(_, Nothing) -> failure "E_QTY" ("quantity out of range: " ++ quantity)
(Just unit, Just count) -> success (total unit count)
_ -> failure "E_SYNTAX" "expected: PRICE <sku> <quantity>"
readQuantity :: String -> Maybe Int
readQuantity text
| null text = Nothing
| length text > 3 = Nothing
| not (all isDigit text) = Nothing
| value < 1 = Nothing
| otherwise = Just value
where
value = read text
total :: Int -> Int -> Int
total unit count
| gross >= 2000 = gross * 9 `div` 10
| otherwise = gross
where
gross = unit * count
success :: Int -> String
success cents = printf "OK %d %s" cents (money cents)
failure :: String -> String -> String
failure code message = "ERR " ++ code ++ " " ++ message
money :: Int -> String
money cents = printf "%d.%02d" (cents `div` 100) (cents `mod` 100)
Three details carry the protocol. respond returns String and never throws, so every failure is a line the caller can read; the money is an Int of cents and the formatting happens once, at the end, with printf "%d.%02d"; and the discount is integer arithmetic, so 2925 becomes 2632 and not 2632.4999999.
The module imports Data.Char and Text.Printf and nothing else, both from base. There is no package to install and no version to pin, which is what lets all three layers of this set build in an image with no network.
The executable that answers
The loop is deliberately written out. isEOF asks whether the input is finished, getLine reads one line and putStrLn writes the answer, and hSetBuffering stdout LineBuffering makes the answer leave the process at the newline instead of at the end of the buffer. That last line is the difference between a protocol server and a program that prints at the end.
module Main (main) where
import Pricing (respond)
import System.IO (BufferMode (LineBuffering), hSetBuffering, isEOF, stdout)
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
loop
where
loop = do
done <- isEOF
if done
then pure ()
else do
line <- getLine
putStrLn (respond line)
loop
Why not interact
The shortest version of this program is two lines and it is wrong for the protocol:
module Main (main) where
import Pricing (respond)
main :: IO ()
main = interact (unlines . map respond . lines)
interact is getContents followed by putStr, and getContents is lazy: it can read the input while the output is being consumed, but a client that sends one line and waits for the answer before sending the next never lets the input end, so the answer waits too. The check below starts each binary, writes one request, flushes the pipe and waits one second for an answer:
"""Does the core answer one line while its input stays open?""" import select import subprocess import sys binary = sys.argv[1] proc = subprocess.Popen( [binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1, ) proc.stdin.write("PRICE tea 3\n") proc.stdin.flush() ready, _, _ = select.select([proc.stdout], [], [], 1.0) if ready: print(f"{binary:16s} answer: {proc.stdout.readline().strip()}") else: print(f"{binary:16s} no answer within 1 s") proc.kill()
python3 stream_check.py ./core
python3 stream_check.py ./core-interact
./core answer: OK 750 7.50
./core-interact no answer within 1 s
status 0
Both programs answer the same eight lines when the pipe closes, which is what the session on the previous page shows. Only one of them answers while the pipe is open, and a line protocol over a socket or a pair of pipes needs the second one.
The build and the session
Two sources, one command, no project file: ghc follows the import from Main to Pricing and compiles both. The build is clean under -Wall.
ghc -Wall -O1 -o core Main.hs Pricing.hs; echo "status $?"
[1 of 3] Compiling Pricing ( Pricing.hs, Pricing.o )
[2 of 3] Compiling Main ( Main.hs, Main.o )
[3 of 3] Linking core
status 0
Then the pipe from the protocol page, which is the whole integration test of the executable:
printf 'PRICE tea 3\nPRICE coffee 3\nPRICE cake 1\nPRICE gold 1\nPRICE tea 0\nPRICE tea 1000\nPRICE tea\nHELLO WORLD\n' | ./core
OK 750 7.50
OK 2632 26.32
OK 400 4.00
ERR E_SKU unknown sku: gold
ERR E_QTY quantity out of range: 0
ERR E_QTY quantity out of range: 1000
ERR E_SYNTAX expected: PRICE <sku> <quantity>
ERR E_SYNTAX expected: PRICE <sku> <quantity>
What the compiler and hlint say
-Wall has nothing to report, and hlint says No hints on all three modules: the price list has a signature, the helpers in the where block of respond are local, and the quantity reader is total. The only trap the compiler cannot see is the one the protocol disposes of: read on a text that is not a number, which the digit guard makes unreachable.
The core is finished and it is the smallest part of the project. The rest of the set is about the two ways to call it and the one way to test it. The next page starts the executable from Python and puts HTTP in front of it. The Haskell lesson behind the loop is standard input and output.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev