Haskell implicit conversions

為{幸葍}努か 提交于 2021-02-09 07:00:45

问题


Hello i was looking to using Data.Text.intercalate and from Hackage i do not understand why if the method has the following signature:

intercalate :: Text -> [Text] -> Text

Why then, does this work

T.intercalate "NI!" ["We", "seek", "the", "Holy", "Grail"]
"WeNI!seekNI!theNI!HolyNI!Grail" 

Shouldn't you apply Data.Text.pack it before each element of the list?
Source : http://hackage.haskell.org/package/text-1.2.3.1/docs/Data-Text.html

In my case i want to pack the following :

Input :"{" ,mytext ,"}" #mytext::Text
I am doing it with :
Prelude.intercalate (Data.Text.pack ",") [pack "{",mytext, pack "}"] or

(pack "{") ++ mytext++ pack "}")
Can someone please explain me why does Data.Text expose the same methods as Data.List (in our case intercalate) and how does it make implicit conversions between Char and Text ?


回答1:


You likely enabled -XOverloadedStrings (or enabled it with the {-# LANGUAGE OverloadedStrings #-} at the top of the file).

As a result this means that string literals (not string variables, only the literals), can be interpreted by any IsString type.

Text is an IsString type. So that means that implicitly you use pack around the string literals (again literals, not ordinary variables).

A similar thing happens with number literals: a number literal can be any Num type. Based on what functions you call on the number literal, Haskell can derive the exact type, and thus "interprets" the literal accordingly. For example if you write atan2 1 2, then 1 and 2 should be interpreted as RealFloat types, whereas for quot 1 2, the 1 and 2 are interpreted as Ìntegral` types.



来源:https://stackoverflow.com/questions/52743607/haskell-implicit-conversions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!