inputfunctional-programmingpure-function

Getting I/O in a functional program


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?


Solution

  • 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.