if-instance: Branch on whether a constraint is satisfied

This is a package candidate release! Here you can preview how this package release will appear once published to the main package index (which can be accomplished via the 'maintain' link below). Please note that once a package has been published to the main package index it cannot be undone! Please consult the package uploading documentation for more information.

[maintain] [Publish]

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.

Properties

Versions 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.3.1.0, 0.4.0.0, 0.5.0.0, 0.5.1.0
Change log changelog.md
Dependencies base (>=4.15.0 && <4.19), ghc (>=9.0 && <9.8), ghc-tcplugin-api (>=0.9 && <0.10), 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 2023-01-24T12:50:32Z

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