3 ms·
If we take familiarity out of the equation, why is a web server inherently better implemented in an imperative style rather than a functional one using monads?
by ParetoOptimal 3y ago
If we take familiarity out of the equation, why is a web server inherently better implemented in an imperative style rather than a functional one using monads?
- markisus 3y agoFamiliarity is part of the equation. Writing an efficient web server requires being familiar with the imperative model since the underlying specs, protocol reference implementations, and libraries are probably given in imperative style. Familiarity aside, using a monadic style introduces constraints in your code. I concede that sometimes those constraints will protect you. But for most use cases, these constraints will just produce nuisance compiler errors, forcing you to write dummy wrapper functions to coerce certain types into other types. Consider the example of a loop whose condition and body are dependent on user input and a global state variable. global max_iterations = 100 def get_messages(): iterations = 0 messages = [] while input() != 'quit' and iterations < max_iterations: messages.append(input()) iterations += 1 Writing this in monadic style requires much more finesse. The global variable must be eliminated. Then function body has to be represented as an expression of type IO[list[string]]. The loop body evidently has type (bool, int, list[string]) -> IO[(int, list[string])], and the conditional has type int -> IO[bool]. Sequencing the conditional and the body requires a recursive function and then maybe a lift operators to convince the compiler that the types work out. See https://conscientiousprogrammer.com/blog/2015/12/11/24-days-of-hackage-2015-day-11-monad-loops-avoiding-writing-recursive-functions-by-refactoring/ https://conscientiousprogrammer.com/blog/2015/12/11/24-days-...