# Coerce for constant time newtype lists

October 29, 2016

haskell has a coerce function. It’s pretty cool!

in the haskell wiki, it talks about how newtypes incur no runtime cost, but when you have an array of newtypes, a runtime cost will still happen in order to instantiate the array of newtypes. Basically, a linear operation of noops will occur. This can be avoided by using coerce.

import Data.Monoid
import Data.Coerce

-- Without coerce, a linear cost:
x, y, z :: Sum Int
x = [Sum 1, Sum 7, Sum 10000]

-- which is basically the same as:
y = map Sum [1,7,10000 :: Int]

-- With coerce, it becomes an O(1) operation:
z = coerce [1,7,10000 :: Int]
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.3738352954387665, "perplexity": 7237.124059906735}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2018-05/segments/1516084887423.43/warc/CC-MAIN-20180118151122-20180118171122-00100.warc.gz"}