#Haskell refusing to compile: Couldn't match type: [Char] with: Either Char String

15 messages · Page 1 of 1 (latest)

fleet willow
#

been trying to wrap my head around this problem for a while, i was working on https://exercism.org/tracks/haskell/exercises/rna-transcription
with the idea of an inner function that recurses to iterate over the input (so that i can return the wrong character like it asks)
but for some reason Either refuses to match the types I'm returning


toRNA :: String -> Either Char String
toRNA xs = inner xs ""
  where
    inner :: String -> String -> Either Char String
    inner st out = case st of
                      "" -> out
                      (x:xs) -> case x of
                                  'G' -> inner xs (out ++ "C")
                                  'C' -> inner xs (out ++ "G")
                                  'T' -> inner xs (out ++ "A")
                                  'A' -> inner xs (out ++ "U")
                                  x -> x```

my thinking is that i can recurse like this
inner "AGT" ""  ->  inner "GT" "U"  ->  inner "T" "UC"  ->  inner "" "UCA"  ->  "UCA"
or on a wrong character:
inner "AX" "" -> inner "X" "U" -> 'X'

but I can't even get the compiler to accept my code due to some type issue that I can't wrap my head around with Either

it keeps giving me compiler errors like ```
/mnt/exercism-iteration/src/DNA.hs:10:29: error:
    • Couldn't match type: [Char]
                     with: Either Char String
      Expected: Either Char String
        Actual: String
    • In the expression: out
      In a case alternative: "" -> out

I don't understand this, isnt String the same as [Char]?

Exercism

Can you solve RNA Transcription in Haskell? Improve your Haskell skills with support from our world-class team of mentors.

#

not central to the problem but I'm very new to Haskell and FP in general, I'm mostly used to python and C

twilit adder
#

String is [Char]

#

But not Either

#

You aren’t using Either in your example

#

In your case "" -> out, out is a String

#

But you said you’d return Either Char String

#

Either doesn’t work like a|b in languages like TypeScript: you need to mark which branch it is.

#

On the other hand, Either allows things like Either Char Char (whereas char|char is nonsensical)

fleet willow
#

okay, i misunderstood what Either did, how do i tell the compiler which branch I'm going to return

twilit adder
#

Either has two constructors: Left (error) and Right

#

So Right 1 is of type Either _ Int, and Left "a" is of type Either String _

fleet willow
#

okay okay so Either Char String is still correct since Char is the error state in this case, i need to wrap my return values with Right and Left as functions to make sure they are the right type?

twilit adder
#

Yes

fleet willow
#

alright, I got all the tests to pass, thank you a lot for the help, I'm not used to a lot of this