Skip to content

Commit 28b1e28

Browse files
authored
expand README (#11)
1 parent 46725d9 commit 28b1e28

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,3 +125,49 @@ For example, a `CallableWithReturnType{Float32}` is guaranteed to return a
125125
`Float32` value, if a value is returned. A
126126
`CallableWithTypeSignature{Float32, Tuple{Float32, Float32}}` additionally
127127
guarantees to only accept exactly two `Float32` values as positional arguments.
128+
129+
For example, suppose your package has a method that accepts a function from the
130+
user. Further suppose the method code expects the user-provided function to only
131+
ever return `Float64`. Instead of sprinkling typeasserts all over your code, it
132+
suffices to call `typed_callable` once:
133+
134+
```julia
135+
function accepts_a_function_from_the_user(func, other_arguments...)
136+
func = typed_callable(Float64, func)
137+
# any call of `func` is now guaranteed not to return anything other than `Float64`
138+
end
139+
```
140+
141+
Furthermore, dispatch can also be used to achieve type safety in this regard:
142+
143+
```julia
144+
function accepts_a_function_from_the_user_type_safe(func::CallableWithReturnType{Float64}, other_arguments...)
145+
# any call of `func` is guaranteed not to return anything other than `Float64`
146+
end
147+
148+
function accepts_a_function_from_the_user(func, other_arguments...)
149+
func = typed_callable(Float64, func)
150+
accepts_a_function_from_the_user_type_safe(func, other_arguments...)
151+
end
152+
```
153+
154+
### Why not just use an inline closure with a `typeassert`?
155+
156+
Creating a new local function with a typeassert in the method body would work as
157+
intended for both:
158+
159+
* helping the compiler achieve good inference
160+
161+
* wrapping a user-provided function into a type-safe wrapper function
162+
163+
However using `typed_callable` instead is slightly better:
164+
165+
* avoiding the creation of a new function is slightly friendlier to the compiler,
166+
giving it less work to do
167+
168+
* using a standardized type may allow the ecosystem to converge on a single type to
169+
dispatch on when a callable with a certain type signature is required
170+
171+
* This is more so appropriate as `CallableWithReturnType` is just a type alias
172+
for a type already provided by `Base`. Thus a package doesn't even need to
173+
depend on this package to dispatch on `CallableWithReturnType{ReturnType}`.

0 commit comments

Comments
 (0)