Custom Expands Battery Return

I am trying to create a custom U-turn function that returns my last battery value, for example:

val unfold' : generator:('State -> ('T * 'State) option) -> state:'State -> 'T list * 'State

I managed to do the following:

let unfold' generator state =
    let rec loop resultList state =
        match generator state with
        | Some (value, state) -> loop (value :: resultList) state
        | None -> (List.rev resultList), state
    loop [] state

But I wanted to avoid the List.revresulting list and generate it with the correct order. I suppose it will be necessary to use continuations to create a list, but I am completely new to functional programming and have not yet been able to get around my thoughts on continuations; and all the alternatives that I can imagine would put the battery in the resulting list or not allow it to return a function.

Is there any way to do this?

Since this is an exercise for personal instruction, I would prefer an answer explaining how to do this, rather than just filling in the code.

+4
2

List.rev resultList. buildResultList. , , , , , .. . ( ), . , , , .

, , , "". "", "" (head:: tail, Lisp -style), - . , , , . , , , , .

, , - : seq, yield , yield!. , "" . , , List.ofSeq , ? , , List.ofSeq : , . F # : , .

, , , . .NET(aka IEnumerable<_>, Seq<_> - ), : , . , , , . (.. Head:: tail), , , , "" , , :

type LazySeq<'t> = LazySeq of (unit -> LazySeqStep<'t>)
and LazySeqStep<'t> = Empty | Cons of head: 't * tail: LazySeq<'t>

- , . , head, tail. .

+5

Fyodor Soikin , :

let unfold' generator state =
    let rec loop build state =
        match generator state with
        | Some (value, state) -> loop (fun newValue -> build (value :: newValue)) state
        | None -> (build []), state
    loop id state
+2

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


All Articles