I picked this exercise to get my hands on Roc. I usually implement interpolation search and compare it with the binary search from the standard library. But I could not find one in Roc, so I implemented both.
I would appreciate it a lot if you could review it: https://github.com/vgaspary/interpolation_search_roc
Here is the (non exhaustive) list of the questions I have so far:
trait InterpolationFactor : Ord, meaning _"Interpolation search would only work on arrays with elements that are InterpolationFactor, which in turn assumes Ord.InterpolationSearch.roc is a custom wrapper of a builtin type. It would be great to be able to perform inteprolation search on an array of numbers, or strings, or timestamps. These types do have the properties needed, but we have to define the "how".List as a span on a contiguous memory? Are lst.take_first(n) and its drop counterpart equivalent to taking a subspan (slice)?Abilities? Traits? Typeclasses? As I understand this is no longer a thing in Roc. Is there a way of expressing the ability dependency? In a similar [Rust crate])https://github.com/vgaspary/interpolation_search/blob/master/src/interpolation_factor.rs) of mine I define
trait InterpolationFactor : Ord, meaning _"Interpolation search would only work on arrays with elements that areInterpolationFactor, which in turn assumesOrd.
I guess it can be solved by defining the type as List(item) which extracts the item type into the item type variable. Then add the constraint on that type variable.
Extending abilities of builtin types? The furthest I came in
InterpolationSearch.rocis a custom wrapper of a builtin type. It would be great to be able to perform inteprolation search on an array of numbers, or strings, or timestamps. These types do have the properties needed, but we have to define the "how".
It's currently not possible to add associated methods to builtin types. If you need overloading, I guess the best option is to supply the comparison function as a parameter. Or start a new thread to discuss a new language feature. Something like a a match, but with types.
List underlying data structure: Is it ok to think of a
Listas a span on a contiguous memory? Arelst.take_first(n)and itsdropcounterpart equivalent to taking a subspan (slice)?
Yes. Unlike in most functional languages, Roc List is actually an array under the hood, not a linked list. The optimizer slices into that backing array when possible, so take/drop first/last and get is very fast. For deleting an elem in the middle, there's List.drop_swap, but it's only usable when ordering is not important. On the other hand, append has worse performance, because it sometimes need to reallocate a new backing array, and prepend has even worse, because it needs to memcpy the items in addition to sometimes reallocating (except if the list had a drop_first called earlier, because in that case it has empty space before the first item).
See also List.prefetched and List.reserve for performance optimizations. Note that these are pure functions from the viewpoint of the program, and only affect the performance of the runtime, not the logic of your program, so you can freely experiment with putting these in various places.
I don't know if there's a list method that preallocates the backing memory, but places the current items at the end, so List.prepend is fast. If there is none currently, maybe it's worth adding? @Richard Feldman, what do you think?
notramo said:
I don't know if there's a list method that preallocates the backing memory, but places the current items at the end, so
List.prependis fast. If there is none currently, maybe it's worth adding? Richard Feldman, what do you think?
there is not currently. I have a vague intution that this could already be implementable using some combination of allocating and then backing it with a seamless slice, but I haven't investigated it and I don't think it's the right thing for me personally to prioritize, given how much I still have left to do for 0.1.0 and this is just for an exercise anyway (and not blocking real-world projects)
:smile:
Thanks everyone for the help!
Aliases are great. I changed the code to make use of them. But since I can't extend built-in types, I changed interpolation_search to expect an interpolation_factor : a, a, a -> F32 function as the first parameter. I understand that Roc has no currying, but it still "feels right" to make this param the first one (since its most likely to be bound, as I demonstrate in the tests).
InterpolationSearch :: [].{
a.Comparable : where [a.is_lt : a, a -> Bool, a.is_lte : a, a -> Bool]
interpolation_search : (a, a, a -> F32), List(a), a -> U64 where [a.Comparable]
interpolation_search = |interpolation_factor, lst, target| match lst {
[] => 0
[only] if only < target => 1
[_] => 0
[first, ..] if target <= first => 0
[.., last] if last < target => lst.len()
[first, .., last] => {
f = interpolation_factor(first, target, last)
mid_idx = ((lst.len() - 1).to_f32() * f).to_u64_wrap()
match lst.get(mid_idx) {
Ok(mid) => if !(mid < target) {
interpolation_search(interpolation_factor, lst.take_first(mid_idx), target)
} else {
interpolation_search(interpolation_factor, lst.drop_first(mid_idx + 1), target) + mid_idx + 1
}
_ => crash "`interpolation_factor` must return an F32 value in [0.0, 1.0] range."
}
}
}
# Tests
## Dec
interpolation_factor_dec = |a, b, c| (b - a) / (c - a)
interpolation_search_dec = |lst, target| interpolation_search(interpolation_factor_dec, lst, target)
expect interpolation_search_dec([1.0.F32, 2.0, 3.0], 0.0) == 0
expect interpolation_search_dec([1.0.F32, 2.0, 3.0], 1.0) == 0
expect interpolation_search_dec([1.0.F32, 2.0, 3.0], 2.0) == 1
expect interpolation_search_dec([1.0.F32, 2.0, 3.0], 3.0) == 2
expect interpolation_search_dec([1.0.F32, 2.0, 3.0], 4.0) == 3
## I32
interpolation_factor_i32 = |a, b, c| (b - a) / (c - a)
interpolation_search_i32 = |lst, target| interpolation_search(interpolation_factor_i32, lst, target)
expect interpolation_search_i32([1, 2, 3, 3, 3, 4, 5, 6], 0) == 0
expect interpolation_search_i32([1, 2, 3, 3, 3, 4, 5, 6], 3) == 2
## Custom type
Item := { val : F32 }.{
is_lt : Item, Item -> Bool
is_lt = |a, b| a.val < b.val
is_lte : Item, Item -> Bool
is_lte = |a, b| a.val <= b.val
}
interpolation_factor_item : Item, Item, Item -> F32
interpolation_factor_item = |a, b, c| (b.val - a.val) / (c.val - a.val)
interpolation_search_item = |lst, target| interpolation_search(interpolation_factor_item, lst, target)
test_list : List(Item)
test_list = [{ val: 1.0 }, { val: 2.0 }, { val: 3.0 }]
expect interpolation_search_item(test_list, Item.{ val: 2.0 }) == 1
}
If you want a shorter parameter list, create a closure over the comparator function, and name it.
It's like manual currying.
I'm not sure I follow. You mean interpolation_search also takes the is_lt and is_lte (or a unified compare : a, a -> [Less, Equal, Greater]) as the fourth parameter?
And then this?
compare_dec = |a, b| crash "not implemented"
interpolation_factor_dec = |a, b, c| (b - a) / (c - a)
interpolation_search_dec = |lst, target| interpolation_search(compare_dec, interpolation_factor_dec, lst, target)
Sorry, I just took a quick glance a the snippet, it's already good.
Sorry for the confusion.
No worries. Thanks for confirming.
I'm not familiar with interpolation search, but it seems that you could use the same implementation for all number types.
https://roc-lang.org/docs/main/langref/types/#where-clauses
https://roc-lang.org/docs/main/langref/operators/#desugaring
If only - and / is used, it's even possible that you don't need the custom comparator function at all, for builtins.
Correct. In my Rust implementation I use a macro to implement that trait for all numeric types.
I could try something like this:
interpolation_factor_numeric : a, a, a -> Bool where [a.minus : a, a -> a, a.to_f32 : a -> F32]
Also, div_by, if you use /.
Perhaps I could even try another generic variant that covers the case of Timestamp-like types, where minus operator returns a value of another type.
interpolation_factor_timestamp_like : a, a, a -> Bool where [a.minus : a, a -> b, a.plus : a, b -> a, b.div_by : b, b -> f32]
But the last condition seems like a long shot. I'm not sure if there are Timestamp and Duration types in Roc standard library, but I don't expect this Duration to have div_by that returns F32.
Time-related structs are in the platforms currently.
But if those structs have the necessary methods, it should work too.
I want to convert the numbers to F32 first to be able to do meaningful divisions. Note that in interpolation_factor = |a, b, c| ... it's assumed that a <= b <= c. This function returns b's position between a and c as a [0.0, 1.0] fraction. Thus, in the following formula the numerator is <= the denominator: (b - a) / (c - a).
notramo said:
Time-related structs are in the platforms currently.
Right. I'm working on another project in parallel, building a reverse proxy in Roc. The word "platform" rings a bell. I think I'm using "the webserver platform". IIUC, there are multiple different platforms (webserver, cli), and you only choose one per project (so it's not like a library).
Is my understanding correct? If so, what does it mean that "Time -related structs are in the platform"? Which platform (and how many are there)?
https://github.com/lukewilliamboswell/roc-awesome#roc-platforms
https://roc-lang.org/faq#multiple-platforms
basic-webserver doesn't have a duration, because no API uses that.
It has a timestamp:
https://roc-lang.github.io/basic-webserver/0.20.0/UnixTime/#UnixTime.Timestamp
But it would not work with the sorting, because it's not trivial what to_f32 would contain. Seconds? Milliseconds? Nanoseconds?
So it's only possible to convert with the more descriptively named functions.
@notramo , big thanks for the links!! I got some reading to do, to understand platforms better.
Start with this: https://roc-lang.org/docs/main/langref/platforms/
A related question, I guess, is there a concept of a library? In Rust for example, I shipped my implementation of interpolation search as a crate, and anyone can add that to their project, find/replace it with their binary_search calls.
What would be a good way of shipping this piece of code? Does it have to belong in one of the platforms?
It's called a "package".
Search for it here:
https://roc-lang.org/docs/main/
In the "Guides & examples" section.
Or find in the sidebar.
Thanks, will do, and I'll report back once I changed the code as per your suggestion above and shipped it as a package.
I'm not sure how valuable my suggestion is, as I'm not familiar with the algorithm, and only superficially looked at the code. And it's late in the night here, I'm quite tired.
But I recommend trying it, at least for learning how Roc type system works.
@notramo , I just reworked the implementation, tried the "default factor function for numbers", and it worked beautifully! Check it out.
At first, I tried overloading interpolation_search, but that's not a thing in Roc, is it? I'm not sure what the correct term is, in C++ it's template specialization, in Rust I think it's called bounded polymorphism. Basically, it'd be great to be able to define a generic implementation, that takes a functor like this:
a.Comparable : where [a.is_lt : a, a -> Bool]
interpolation_search : (a, a, a -> F32), List(a), a -> U64 where [a.Comparable]
and then add some specializations, possibly with different parameter set (the name is the same, but the first arg is missing):
a.Numeric : where [a.Comparable, a.minus : a, a -> a, a.to_f32 : a -> F32]
interpolation_search : List(a), a -> U64 where [a.Numeric]
and even specialize all the way
interpolation_search : List(Str), Str -> U64
Do you know, if what I describe above is doable with today's feature set?
Hi @Vanand Gasparyan,
I had Claude Opus 5.5 draft a reply which has been reviewed and edited by me:
where clauses get you most of what you're after: any type that has the right methods fits automatically, including your own types, and there's no "impl" to declare.
Here's a shape that covers all builtin numbers and also your timestamp idea:
InterpolationSearch :: [].{
a.Comparable : where [a.is_lt : a, a -> Bool]
# Fully general: the caller provides the factor.
search_with : List(a), a, (a, a, a -> F64) -> U64 where [a.Comparable]
search_with = |lst, target, factor| ... # your current body, using to_f64
# Builtin numbers, plus any of your own types with is_lt, minus and to_f64.
search : List(a), a -> U64 where [a.Comparable, a.minus : a, a -> d, d.to_f64 : d -> F64]
search = |lst, target| search_with(lst, target, |lo, x, hi| x.minus(lo).to_f64() / hi.minus(lo).to_f64())
expect search([1, 2, 3, 3, 3, 4, 5, 6], 3) == 2
expect search([1.5, 2.5, 3.5], 2.5) == 1
# Timestamp-like: `minus` returns a different type, no factor function needed
expect {
Duration := { secs : I64 }.{
to_f64 = |d| d.secs.to_f64()
}
Timestamp := { secs : I64 }.{
is_lt = |a, b| a.secs < b.secs
minus : Timestamp, Timestamp -> Duration
minus = |a, b| { secs: a.secs - b.secs }
}
times : List(Timestamp)
times = [{ secs: 100 }, { secs: 200 }, { secs: 300 }, { secs: 400 }]
search(times, Timestamp.{ secs: 300 }) == 2
}
}
Two gotchas I ran into while writing this:
x.minus(lo), not x - lo. The - operator always returns the left operand's type, so it can't turn two Timestamps into a Duration.a.Interpolatable(d) : where [..., d.to_f64 : d -> F64] is rejected. That's why the constraints are written out inline.For List(Str): Roc strings don't support < (there's no is_lt), so a string version can't go through Comparable. You'd need a separate search_str, or a variant that also takes the comparison as a function (like your binary_search takes pred), and compare the to_utf8() bytes yourself.
Anton said:
Two gotchas I ran into while writing this:
- It has to be
x.minus(lo), notx - lo. The-operator always returns the left operand's type, so it can't turn twoTimestamps into aDuration.- A where alias can only constrain its own receiver, so
a.Interpolatable(d) : where [..., d.to_f64 : d -> F64]is rejected. That's why the constraints are written out inline.
these may be possible to relax in the future - I can look into it after the 0.1.0 release lands :smile:
The left-operand pitfall comes up in one of my repos FWIW. I have opaque types that distinguish Place from Distance in my app. Those would be overkill in most apps, but a huge part of my app is about place/distance arithmetic. The workarounds are clear enough, so this is just a data point.
yeah I started out with it being just x - lo literally desugared to x.minus(lo) with no extra constraints, but there were unexpected downsides. I remember confusing error messages in typical cases (where you're using them for normal builtin numbers) being one of the downsides but I think there were more.
it might be possible to address the downsides in a different way, but it's an involved enough project that I don't want to tackle it until after 0.1.0
Thanks @Anton , that's very helpful. I actually tried defining an alias with a.minus : a, a -> d, exactly like yours, the compiler didn't like it, and I didn't think of trying inline.
It's funny that Claude also brought up strings. I was trying to support strings earlier today and that led me to discover Roc's complicated relationship with Strings. :smile: This page is a great summary of all the nuances that make strings a nightmare. As a stickler for rigor I like it when languages (and standard libraries) highlight the inherent complexity of things instead of hiding or ignoring them. Examples that come to mind are Rust's mutex lock or that f64 is not Ord. Unfortunately, most people find these kinds of things unapproachable. Looking at this len : Str -> [LearnAboutStringsInRoc(Str)] I couldn't help but think of this. :smile:
@Richard Feldman , I found this from some time ago, and I understand how _function overloading_ and _type inference_ are at odds. What about function overload by the number of parameter count? That is, you can have many foo_bars, but with different number of parameters. Was this considered? Is it a thing in any other language?
it was considered, yeah - Clojure and Elixir have arity-based overloads
it doesn't have the performance problem, but I just don't think it's worth doing
I don't think "default arguments" are worth doing either, which are kind of a special case of multi-arity functions
I remember "default arguments" being annoying from C++, when more than one are such. Better not go there.
Vanand Gasparyan said:
Looking at this
len : Str -> [LearnAboutStringsInRoc(Str)]I couldn't help but think of this. :smile:
amusingly, we actually do support a variety of ways to exit the repl, because there's no footgun there - it just exits - unlike string length, which can cause bugs :smile:
Python's official philosophy on this point is "There should be one-- and preferably only one --obvious way to do it." It's only about obvious ways to do it. Plus, it's not strict: it's just a preference.
Ruby is a fun language, and its do-it-your-way philosophy is great when you're working on a personal project or when you need a DSL, but in my experience it doesn't scale well in large projects, at least in the Ruby projects I worked on: my colleagues were having way too much fun defining layers upon layers of "cool" abstractions and DSLs that were only used in one place. And this go-wild philosophy also extended to the ecosystem, where packages had new breaking changes every other day. More freedom is great when it doesn't translate to messy and unstable code. We didn't have this issue with Python projects.
Last updated: Nov 26 2026 at 20:35 UTC