Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add extra map, bind and join operators. #16

Open
tmcgilchrist opened this issue May 24, 2023 · 1 comment
Open

Add extra map, bind and join operators. #16

tmcgilchrist opened this issue May 24, 2023 · 1 comment

Comments

@tmcgilchrist
Copy link
Member

tmcgilchrist commented May 24, 2023

What do you think about adding some more fundamental operators to this library @talex5 ?
In writing some documentation on using this library outside of ocurrent I ended up defining the following functions.

val map2 : ?eq:('c -> 'c -> bool) -> ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
val bind : ?eq:('b -> 'b -> bool) -> ('a -> 'b t) -> 'a t -> 'b t
val join : ?eq:('a -> 'a -> bool) -> 'a t t -> 'a t

Then you can write code like this in a more natural style.

let rec merge ar ~f =
    if Array.length ar <= 1 then ar.(0)
    else
      let len = Array.length ar in
      let len' = len / 2 + (len mod 2) in
      let ar' =
        Array.init len' (fun i ->
          if i * 2 + 1 >= len then ar.(i*2)
          else Current_incr.map2 f ar.(i*2) ar.(i*2+1))
      in
      merge ar' ~f
      
let average ar =
  let sum = merge ar ~f:(+.) in
  Current_incr.map (fun s -> s /. float (Array.length ar)) sum      
 
 let average_of_prefix ar length =
    Current_incr.bind (fun length ->
      average (Array.init length (fun i -> ar.(i)))) length 
@talex5
Copy link
Contributor

talex5 commented May 24, 2023

If you're going to add that, it might be better to use the new let syntax instead, e.g.

let average ar =
  let sum = merge ar ~f:(+.) in
  Current_incr.map (fun s -> s /. float (Array.length ar)) sum 

becomes

let average ar =
  let+ sum = merge ar ~f:(+.) in
  sum /. float (Array.length ar))

Not sure it's worth it, given how small the library is at present, but we did already add map.

https://discuss.ocaml.org/t/ann-current-incr-a-small-incremental-library-with-no-dependencies/5531/7?u=talex5 notes that writing code this way may be a little less efficient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants