if-instance: Branch on whether a constraint is satisfied

[ bsd3, library, plugin, type-system ] [ Propose Tags ] [ Report a vulnerability ]

This library provides a mechanism that can be used to branch on whether a constraint is satisfied (not limited to typeclass instances).

Usage example:

{-# OPTIONS_GHC -fplugin=IfSat.Plugin #-}

module MyModule where

import Data.Constraint.If ( IfSat(ifSat) )

hypot :: forall a. ( Floating a, IfSat (FMA a) ) => a -> a -> a
hypot = ifSat @(FMA a) withFMA withoutFMA
  where
    withFMA :: FMA a => a -> a -> a
    withFMA x y =
      let
        h = sqrt $ fma x x (y * y)
        h² = h * h
        x² = x * x
        u = fma (-y) y (h² - x²) + fma h h (-h²) - fma x x (-x²)
      in
        h - u / ( 2 * h )
    withoutFMA :: a -> a -> a
    withoutFMA x y = sqrt ( x * x + y * y )

Here we select between two ways of computing the hypotenuse function based on whether we have access to the fused multiply-add operation

 fma :: FMA a => a -> a -> a -> a

which computes \ x y z -> ( x * y ) + z in a single instruction, providing stronger guarantees about precision of the result.

A call of the form hypot @MyNumberType will either use the robust withFMA function when an FMA MyNumberType instance is available, or will fallback to the simple withoutFMA implementation when no such instance can be found.

library if-instance

Modules

[Index] [Quick Jump]

library if-instance:if-instance-example

Modules

[Index] [Quick Jump]

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

  • No Candidates
Versions [RSS] 0.1.0.0, 0.2.0.0, 0.2.1.0, 0.2.1.1, 0.3.0.0, 0.3.1.0, 0.4.0.0, 0.5.0.0, 0.5.1.0, 0.5.2.0 (info)
Change log changelog.md
Dependencies base (>=4.15.0 && <4.22), ghc (>=9.0 && <9.14), ghc-tcplugin-api (>=0.13 && <0.15), if-instance [details]
License BSD-3-Clause
Copyright 2021 Sam Derbyshire
Author Sam Derbyshire
Maintainer Sam Derbyshire
Category Type System, Plugin
Home page https://github.com/sheaf/if-instance
Uploaded by sheaf at 2024-11-29T12:37:47Z
Distributions
Downloads 765 total (37 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2024-11-29 [all 1 reports]