3 people like it.

Repeat until

Repeatedly call a function until it returns a positive result. Implemented using sequences.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let repeatUntilSome f =
    Seq.initInfinite (fun _ -> f())
    |> Seq.find Option.isSome
    |> Option.get

let repeatUntilTrue f =
    Seq.initInfinite (fun _ -> f())
    |> Seq.find id
    |> ignore
val repeatUntilSome : f:(unit -> 'a option) -> 'a

Full name: Script.repeatUntilSome
val f : (unit -> 'a option)
module Seq

from Microsoft.FSharp.Collections
val initInfinite : initializer:(int -> 'T) -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.initInfinite
val find : predicate:('T -> bool) -> source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.find
module Option

from Microsoft.FSharp.Core
val isSome : option:'T option -> bool

Full name: Microsoft.FSharp.Core.Option.isSome
val get : option:'T option -> 'T

Full name: Microsoft.FSharp.Core.Option.get
val repeatUntilTrue : f:(unit -> bool) -> unit

Full name: Script.repeatUntilTrue
val f : (unit -> bool)
val id : x:'T -> 'T

Full name: Microsoft.FSharp.Core.Operators.id
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
Raw view Test code New version

More information

Link:http://fssnip.net/5Y
Posted:13 years ago
Author:Johann Deneux
Tags: sequence , control-flow