So I know that you can't directly get input from a user in a functional program because it obviously wouldn't be pure. But does this still apply if the user had only like 4 options to choose from? For instance, is it still impure if you're asking for hair color and there were four options to choose from: Brown, Black, Blonde, Red. If the user were to click a button corresponding to their hair color instead of typing it in, would that be considered pure?
Asked
Active
Viewed 61 times
3
-
If user input is impure then user input is impure, even if the range of possible inputs is restricted. A more interesting question is how do functional languages deal with this impurity. – John Coleman Dec 12 '22 at 23:06
-
I could be wrong but wouldn't it have to do with wrapping the input into something like an Optional<>, etc. This wouldn't necessarily fix the impurity, but it's better than just simply taking an input right? – skiboy108 Dec 13 '22 at 00:08
-
Not all languages handle this equally, but Haskell famously wraps impure values. Not in `Optional`, but in `IO`. Here's an explanation for people comfortable with reading C# code: https://blog.ploeh.dk/2020/06/08/the-io-container – Mark Seemann Dec 13 '22 at 06:24
1 Answers
3
You can't predict what the user is going to choose, making the decision non-deterministic, and hence impure.
User input is essentially a function that has to produce a value out of nothing: () -> HairColor
.
If you have four kinds of HairColor
, you can write exactly four pure functions of that type:
f1 _ = Blonde
f2 _ = Brown
f3 _ = Black
f4 _ = Blue
None of them would, though, capture user input. In order to get the user input, you need another kind of 'argument' to the function:
UserInput -> HairColor
but then, where does UserInput
come from? It's not something you can compile into the program. It has to 'come from the outside', and every time you run the program, it may be different.

Mark Seemann
- 225,310
- 48
- 427
- 736
-
If you force a selection the result set size is `1`, i.e. it isn't the number of results that is indeterministic but the time the selection takes place. The selection itself is an inherently asynchronous event that happens at an arbitrary moment during the runtime. Maybe this is the source of confusion. – Dec 13 '22 at 11:45