Getting I/O in a functional program - input

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?

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.

Related

Detect object at mouse click location

I have a large number of different image stimuli presented in various locations on screen.
When the participant clicks on a stimulus, I need the name of that stimulus item available for use in the rest of the script.
For example, you can achieve this in E-Prime with the SlideState.HitTest(x, y) method, where x and y are mouse coordinates.
The only similar thing I've been able to see in Psychopy is the mouse.isPressedIn(shape) method. However because you must supply a specific object as an argument, it seems you would need an if clause for each of the stimuli, which seems messy (especially for larger numbers of items)
Is there a better way of doing this? I'm still learning so I might be missing something.
Thanks!
No, I think not. However, if you just add all objects to a list and loop over them, the code will be neat enough.
# List of (pointers to) stimulus objects
shapes = [shape1, shape2, shape3, shape4, shape5]
# Loop over them and check if mouse is pressed on each one of them
for shape in shapes:
if mouse.isPressedIn(shape):
# Set this variable to point to the latest pressed shape
pressed_shape = shape
# Now you can do stuff with this object
pressed_shape.fillColor = 'red'
pressed_shape.draw()
print pressed_shape.name
Note that if the mouse clicks at a location where there are two objects, pressed_shape is the latest in the list for this solution.

Cannot read property 'kids' of undefined - or how to break a circular dependency of signals in Elm?

While elm-make succeeds, I get the following error in the browser:
Cannot read property 'kids' of undefined
I assume it's because I have a circular dependency of signals:
model -> clicks -> model
Here is the relevant code:
model : Signal Model
model =
Signal.foldp update initialModel clicks
clicks : Signal Action
clicks =
let
clickPosition = Mouse.position
|> Signal.sampleOn Mouse.clicks
tuplesSignal = Signal.map3 (,,) clickPosition Window.dimensions model
in
...
It feels like model is implemented as a common practice in Elm, so I should challenge the clicks -> model dependency.
Here is some context:
I'm building a sliding puzzle game using canvas:
When user clicks a tile that can move, it should move. Otherwise, the click should be ignored.
clicks will produce the following actions: Left, Right, Up, Down
For example, if user clicks on tiles 12, 11, 8, 15 (in this order), clicks should be: Down -> Right -> Up
The problem is, that in order to calculate which tile was clicked, I need to know the board dimensions (e.g. 4 rows and 4 columns in the picture above). But, board dimensions are stored in the model (imagine user interface that allows users to change board dimensions).
How do I get out of this circular dependency?
In this case I think you should go more low-level in what you call an input, and accept click positions as inputs. Then you can compose an update function in your Signal.foldp out of two others:
The first turns the clicks and model into a Maybe Direction (assuming the Left, Right, Up, Down are constructors of type Direction)
The second function that takes a Direction value and the model to calculate the new model. You can use Maybe.map and Maybe.withDefault to handle the Maybe part of the result of the first function.
Separating these two parts, even though you produce and consume Direction immediately, makes your system more self-documenting and shows the conceptual split between the raw input and the restricted "actual" inputs.
P.S. There are conceivable extensions to the Elm language that would allow you to more easily write this input preprocessing in signal-land. But such extensions would make the signal part of the language so much more powerful that it's unclear if it would make "the right way" to structure programs harder to discover.

Create a Signal from a List

Is it possible to create a Signal from a List? Essentially what I want is something with the signature List a -> Signal a. I know that a Signal represents a time-varying value and so something like this doesn't actually make any sense (i.e. I can't think of a reason to use it in production code).
I could see applications of it for testing though. For example, imagine some function which depended on the past values of a Signal (via foldp for instance) and you wanted to make assertions about the state of the system given the signal had received values x, y, and z.
Note that there wouldn't have to be anything special about the Signal denoting that it only would ever receive a fixed number of values. I'm thinking of it more like: in production you have a Signal of mouse clicks, and you want to test that from a given starting position, after a given set of clicks, the system should be in some other known state. I know you could simulate this by calling the function a fixed number of times and feeding the results back in with new values, I'm just wondering if it is possible.
I guess it's possible. You use a time-based signal, and map the values from the list over it:
import Time
import Graphics.Element exposing (show)
list = [1..10]
signalFromList : List a -> Signal a
signalFromList list =
let
(Just h) =
List.head list
time =
Time.every Time.second
maybeFlatMap =
flip Maybe.andThen
lists =
Signal.foldp (always <| maybeFlatMap List.tail) (Just list) time
in
Signal.filterMap (maybeFlatMap List.head) h lists
main = Signal.map show <| signalFromList list
However!
It shouldn't be hard to do testing without signals. If you have a foldp somewhere, in a test you can use List.foldl over a list [x,y,z] instead. That should give you the ability to look at the state of your program after inputs x, y, z.
I don't think there is any way it can be done synchronously in pure elm (Apanatshka's answer illustrates well how to set up a sequence of events across time and why it's a bad idea). If we look at how most Signals are defined, we'll see they all head down into a native package at some point.
The question then becomes: can we do this natively?
f : List a -> Signal a
I often think of (Signal a) as 'an a that changes over time'. Here we provide a List of as, and want the function to make it change over time for us.
Before we go any further, I recommend a quick look at Native/Signal.js: https://github.com/elm-lang/core/blob/master/src/Native/Signal.js
Let's say we get down to native land with our List of as. We want something a bit like Signal.constant, but with some extra behaviour that 'sends' each a afterwards. When can we do the sending, though? I am guessing we can't do it during the signal construction function, as we're still building the signal graph. This leaves us a couple of other options:
something heinous with setTimeout, scheduling the sending of each 'a' at an appropriate point in the future
engineering a hook into the elm runtime so that we can run an arbitrary callback at the point when the signal graph is fully constructed
To me at least, the former sounds error prone, and I hope the latter doesn't exist (and never does)!
For testing, your suggestion of using a List fold to mimic the behaviour of foldp would be the way I would go.

Turing Machines

I'm reading a book on Languages & Automata and I'm not understanding Turing Machines. I've taught myself about DFA's NFA's and Pushdown Automata without any problems. Can someone please explain what this is doing?
B = {w#w|w ∈ {0, 1}*}
The following figure contains several snapshots of Ml 's tape while it is computing
in stages 2 and 3 when started on input 011000#011000.
Thanks alot!
"Imagine an endless row of hotel rooms, and each room contains a lightbulb and a switch that controls it. Initially, all the rooms are dark. A robot starts at one of the rooms, and has the ability to operate switches and move to adjacent rooms.
The robot has several states that it can be in, and each state determines what it should do based on whether the current room is light or dark. For example, a robot's rules could include these states:
The "scared" state:
If the room is dark, turn on the light and move to the room to the left.
If the room is light, do nothing and go to the "normal" state.
The "normal" state:
If the room is light, turn off the light and move to the room on the right.
Otherwise, go to the "scared" state.
One special state is the "stop" state. When the robot finds itself in this state, the process is complete.
Suppose a robot has n states (not including the "stop" state), and it stops. What is the maximum number of light rooms at this point?
This system is in direct allegory to Turing machines. The hotel is the tape, the robot is the Turing machine, and dark rooms and light rooms are 0 and 1 cells."
It is from googology wiki. I gave an idea to it, but, of course, this text has been improved since me.
Turing machine is a hypothetical machine with a tape where symbols are stored. It can have multiple heads that can read symbols from the tape or write symbols to the tape.
Now your grammar says B = {w#w|w ∈ {0, 1}*}, that is any string of the form "w#w", where w is any combination of 0's and 1's or none at all. So let's say w = 011000 for this particular example. The resulting string will be 011000#011000 and your turing machine will be verifying if it follows this grammar.
Your turing machine has one head in this case. It starts at the beginning of string. Reads the first character which is 0. Mark it "x": meaning I've read this. Then goes immediately after the # and checks if what it just read is matching. In this case it's 0 as well so it marks it as matching "x". It then goes back to previous position and does the same for next character. It keeps doing this until it reaches #. When it reads hash or #, it checks for the end of the string and if it is the end of string, it accepts this string saying yes this follows the given grammar.

Which way to store this data is effective?

I am writing a game, which need a map, and I want to store the map. The first thing I can think of, is using a 2D-array. But the problem is what data should I store in the 2D-array. The player can tap different place to have different reaction. So, I am thinking store a 2D-array with objects, when player click some position, and I find it in the array, and use the object in that array to execute a cmd. But I have a concern that storing lots of object may use lots of memory. So, I am think storing char/int only. But it seems that not enough for me. I want to store the data like that:
{
Type:1
Color:Green
}
No matter what color is, if they are all type 1, the have same reactions in logic, but the visual effect is based on the color. So, it is not easy to store using a prue char/int data, unless I make something like this:
1-5 --> all type 1. 1=color green ,
2=color red, 3 = color yellow.... ...
6-10 --> all type 2. 2 = color green,
2 = color red ... ...
So, do you have any ideas on how to minimize the ram use, but also easy for me to read... ...thx
Go ahead and store a bunch of objects in the array, but with these two refinements:
Store a pointer to the object, not the object itself. (Objective C may handle this for you automatically; I don't know.)
Remember that a pointer to a single object can appear in more than one position in the array. All squares that share the same color and behavior can share an object.
It would also help if you did the math on the size of the array and the number of distinct squares so we can know exactly how much RAM you are talking about.