From b0ab4b99b45f32855058467ad554f7304efdea07 Mon Sep 17 00:00:00 2001 From: "Tamas K. Papp" Date: Thu, 5 Apr 2018 10:00:37 +0200 Subject: [PATCH] Add Fix1 (partial application). Also add some trivial tests, and clarify that this is for two-argument functions in the docstrings. --- base/operators.jl | 23 ++++++++++++++++++++--- test/operators.jl | 9 +++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/base/operators.jl b/base/operators.jl index 1600da1b73078..8cfb5e3f55ac9 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -813,12 +813,29 @@ julia> filter(!isalpha, str) """ !(f::Function) = (x...)->!f(x...) +""" + Fix1(f, x) + +A type representing a partially-applied version of the two-argument function +`f`, with the first argument fixed to the value "x". In other words, +`Fix1(f, x)` behaves similarly to `y->f(x, y)`. +""" +struct Fix1{F,T} <: Function + f::F + x::T + + Fix1(f::F, x::T) where {F,T} = new{F,T}(f, x) + Fix1(f::Type{F}, x::T) where {F,T} = new{Type{F},T}(f, x) +end + +(f::Fix1)(y) = f.f(f.x, y) + """ Fix2(f, x) -A type representing a partially-applied version of function `f`, with the second -argument fixed to the value "x". -In other words, `Fix2(f, x)` behaves similarly to `y->f(y, x)`. +A type representing a partially-applied version of the two-argument function +`f`, with the second argument fixed to the value "x". In other words, +`Fix2(f, x)` behaves similarly to `y->f(y, x)`. """ struct Fix2{F,T} <: Function f::F diff --git a/test/operators.jl b/test/operators.jl index ea6db5cac49f1..10631fceef978 100644 --- a/test/operators.jl +++ b/test/operators.jl @@ -181,3 +181,12 @@ end @test fldmod1(4.0, 3) == fldmod1(4, 3) end + +@testset "Fix12" begin + x = 9 + y = 7.0 + fx = Base.Fix1(/, x) + fy = Base.Fix2(/, y) + @test fx(y) == x / y + @test fy(x) == x / y +end