-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Pitch.Hz module for working with musical pitches in Hertz
- Loading branch information
Bernardo Barros
committed
Jan 31, 2024
1 parent
cdc966a
commit 9b617ee
Showing
2 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,6 +29,7 @@ library | |
Pitch.Parser | ||
Pitch.Pitch | ||
Pitch.QuasiQuoter | ||
Pitch.Hz | ||
Rtm.Common | ||
Rtm.Parser | ||
Rtm.QuasiQuoter | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
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) | ||
|
||
-- Standard pitch (A4) definition in Hertz. | ||
pitchStandard :: Hz | ||
pitchStandard = Hz 440.0 | ||
|
||
-- Convert a `Semitone` or `Double` representing semitones to `Hz`. | ||
-- Works for both integral and fractional semitones. | ||
semitoneToHz :: Double -> Hz | ||
semitoneToHz n = pitchStandard * Hz (2 ** (n / 12.0)) | ||
|
||
-- Convert a frequency in `Hz` to its equivalent in semitones relative to `pitchStandard`. | ||
-- Calculated using the logarithm base 2. | ||
hzToDouble :: Hz -> Double | ||
hzToDouble (Hz hz) = 12.0 * logBase 2 (hz / unHz pitchStandard) | ||
|
||
-- Use `hzToDouble` to convert Hz to `Semitone`. | ||
hzToSemitone :: Hz -> Semitone | ||
hzToSemitone = Semitone . hzToDouble | ||
|
||
-- Directly retrieve the underlying `Double` from a `Semitone`. | ||
semitoneToDouble :: Semitone -> Double | ||
semitoneToDouble (Semitone n) = n | ||
|
||
-- Wrap a `Double` as a `Semitone`. | ||
doubleToSemitone :: Double -> Semitone | ||
doubleToSemitone = Semitone |