2016-06-18 6 views
9

これは本当にうっとうしい質問かもしれませんが、私はこの問題を克服できません。予想されるタイプの `Text 'と実際のタイプ` [Char]'を一致させることができませんでした。

私は、コードの単純なブロックがあります。私はstrでこれを呼び出すと、私が手

module SomeTest where 
import Data.Text 

str = replace "ofo" "bar" "ofofo" 

を:

<interactive>:108:19: error: 
* Couldn't match expected type `Text' with actual type `[Char]' 
* In the first argument of `Data.Text.replace', namely `"ofo"' 
    In the expression: Data.Text.replace "ofo" "bar" "ofofo" 
    In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo" 

<interactive>:108:25: error: 
* Couldn't match expected type `Text' with actual type `[Char]' 
* In the second argument of `Data.Text.replace', namely `"bar"' 
    In the expression: Data.Text.replace "ofo" "bar" "ofofo" 
    In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo" 

<interactive>:108:31: error: 
* Couldn't match expected type `Text' with actual type `[Char]' 
* In the third argument of `Data.Text.replace', namely `"ofofo"' 
    In the expression: Data.Text.replace "ofo" "bar" "ofofo" 
    In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo" 

私は取得していますなぜ私にはわかりませんこのエラーとどのようにそれを渡す得る。 Text[Char]の単なる同義語ではありませんか?

+0

いいえ、「テキスト」は完全に異なるタイプです。しかし、 'String'は' [Char] 'の同義語です。 – melpomene

+2

残念ながら、Haskellには文字列にいくつかの相反するタイプがあります。あなたの場合は、プログラムの最初の行に '{ - #LANGUAGE OverloadedStrings# - }'を追加するとコンパイルするはずです。 – stholzm

+0

ありがとう、これは実際に働いた。このコメントから回答をしてください、私はそれを受け入れます。 –

答えて

18

残念ながら、Haskellには文字列にいくつかの相反するタイプがあります。文字列リテラルは通常、タイプStringであり、[Char]のエイリアスです。これは文字列の非効率的な表現であるため、Textのような選択肢があります。

あなたの場合、プログラムの最初の行に{-# LANGUAGE OverloadedStrings #-}を追加するとコンパイルされます。基本的に、文字列リテラルのタイプはTextです。

+12

'OverloadedStrings'は、すべての文字列リテラル' 'foo''を' fromString "foo" 'に暗黙的に変換します。 ['fromString'](http://hackage.haskell.org/package/base-4.9.0.0/docs/Data-String.html#v:fromString)は、' String'から任意のインスタンスに変換できるメソッドです。 'Text'のような' IsString'クラスです。 – melpomene

+0

ありがとう:)もう一つの素晴らしい情報。 –

+4

GHCは、 "IsString"のどのインスタンスを使用すべきかを判断することができないので、これはうまくいくが、あいまいな型についてはもっと複雑なエラーが出るかもしれない。これらは一般的に "some text"を( "some text" :: Text)に変更することで解決できます。 –

関連する問題