F #: saving and displaying a list of functions

I have a number of events that take place in the game. I want to control the time and order with which these events occur.

For example:

Event 1: Show text on screen for N frames and play sound effect

Event 2: clear text on screen

My solution (maybe better) is a list of functions containing events. Events execute their behavior and then return the following events in the game. I was thinking about using List.map or List.collect, because I essentially map the list of events to the new list of events when I execute some behavior code.

In the above example, Event1 can consist of two functions: one that displays text and one that plays sound (hence the need for a list). The function that displays the text will return a copy for frames N-1, after which it will return Event2, which will clear the text. The sound reproduction function will return the no-op equivalent.

If this is a good solution, maybe I could do it in C ++ or C #. My goal is to make an equivalent or better decision in F #.

+3
source share
5 answers

Did you mean something like this?

let myActions =
    [fun () -> printfn "You've woken up a dragon."
     fun () -> printfn "You hit the dragon for 0 points of damage."
     fun () -> printfn "The dragon belches."
     fun () -> printfn "You have died."] 

let actionBuilder actionList = 
    let actions = ref actionList
    fun () ->
        match !actions with
        | [] -> ()
        | h::t -> h(); actions := t

Usage (F # interactive):

> let doSomething = actionBuilder myActions;;

val doSomething : (unit -> unit)

> doSomething();;
You've woken up a dragon.
val it : unit = ()
> doSomething();;
You hit the dragon for 0 points of damage.
val it : unit = ()
> doSomething();;
The dragon belches.
val it : unit = ()
> doSomething();;
You have died.
val it : unit = ()
> doSomething();;
val it : unit = ()
> 

** : **, , , , , O (N) O (1) :

type actionGenerator(myActions: (unit->unit) list) =
    let Q = new System.Collections.Generic.Queue<_>(Seq.ofList myActions)

    member g.NextAction = 
        fun () -> 
            if Q.Count = 0 then ()
            else Q.Dequeue()()

    member g.AddAction(action) = Q.Enqueue(action)
+5

, ... , . , (unit->(unit->unit)) list (unit->unit) list, . , :

let l = [(fun () -> (fun () -> printfn "first nested fn")); (fun () -> (fun () -> printfn "second nested fn"))]
let l' = List.map (fun f -> f()) l
+2

, :

List<`a->`b>

, .

, , - , , .

"" -

+2

, , , . , , "" , "". , F #, - .

: , ? , ?

, , " ".

? , Haskell, F # , .

, - , . ( ), , , .

, : , , .

+1

, - . , .

Since you are asking this question, I assume that you have more experience in imperative languages. It seems that the real solution to your problem is something completely different than a list of functions.

0
source

Source: https://habr.com/ru/post/1723618/


All Articles