Skip to content

Commit

Permalink
Refactor Hz and Semitone types
Browse files Browse the repository at this point in the history
Bernardo Barros committed Jan 31, 2024
1 parent 9b617ee commit 57fb197
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions src/Pitch/Hz.hs
Original file line number Diff line number Diff line change
@@ -3,31 +3,56 @@ module Pitch.Hz where
-- | The Pitch.Hz module provides types and functions to work with musical pitches in terms of semitones and Hertz.

-- `newtype` wrappers for `Semitone` and `Hz` provide type safety.
newtype Semitone = Semitone {unSemitone :: Double} deriving (Show, Eq, Num, Ord)
newtype Hz = Hz {unHz :: Double} deriving (Show, Eq, Num, Ord)
newtype Semitone = Semitone {unSemitone :: Double} deriving (Eq, Num, Ord)
newtype Hz = Hz {unHz :: Double} deriving (Eq, Num, Ord)

-- Standard pitch (A4) definition in Hertz.
instance Show Semitone where
show (Semitone n) = show n <> " Semitone(s)"

instance Show Hz where
show (Hz hz) = show hz <> " Hz"


-- | Standard pitch (A4) definition in Hertz.
--
-- >>> pitchStandard
-- 440.0 Hz
pitchStandard :: Hz
pitchStandard = Hz 440.0

-- Convert a `Semitone` or `Double` representing semitones to `Hz`.
-- | Convert a `Semitone` or `Double` representing semitones to `Hz`.
-- Works for both integral and fractional semitones.
--
-- >>> semitoneToHz 12
-- 880.0 Hz
semitoneToHz :: Double -> Hz
semitoneToHz n = pitchStandard * Hz (2 ** (n / 12.0))

-- Convert a frequency in `Hz` to its equivalent in semitones relative to `pitchStandard`.
-- | Convert a frequency in `Hz` to its equivalent in semitones relative to `pitchStandard`.
-- Calculated using the logarithm base 2.
--
-- >>> hzToDouble (Hz 880.0)
-- 12.0
hzToDouble :: Hz -> Double
hzToDouble (Hz hz) = 12.0 * logBase 2 (hz / unHz pitchStandard)

-- Use `hzToDouble` to convert Hz to `Semitone`.
-- | Use `hzToDouble` to convert Hz to `Semitone`.
--
-- >>> hzToSemitone (Hz 880.0)
-- Semitone {unSemitone = 12.0}
hzToSemitone :: Hz -> Semitone
hzToSemitone = Semitone . hzToDouble

-- Directly retrieve the underlying `Double` from a `Semitone`.
-- | Directly retrieve the underlying `Double` from a `Semitone`.
--
-- >>> semitoneToDouble (Semitone 12.0)
-- 12.0
semitoneToDouble :: Semitone -> Double
semitoneToDouble (Semitone n) = n

-- Wrap a `Double` as a `Semitone`.
-- | Wrap a `Double` as a `Semitone`.
--
-- >>> doubleToSemitone 12.0
-- Semitone {unSemitone = 12.0}
doubleToSemitone :: Double -> Semitone
doubleToSemitone = Semitone

0 comments on commit 57fb197

Please sign in to comment.