1
votes

I am use Haskell stack.

module Len () where

   my_nthele :: String -> Integer -> Char
   my_nthele [] n = ''
   my_nthele (x:xs) n  | n == 0 = x
                       | otherwise = my_nthele xs (n-1)

Haskell interpreter shows "src/Len.hs:5:1: error: parse error (possibly incorrect indentation or mismatched brackets)"

I have no clue about what is wrong.

1
'' is not a valid character. - user2407038
@user2407038, ah, i see, then how to return a empty char in haskell? - anru
ok, see that, I should use Maybe - anru
See also at* from the safe package. - Daniel Wagner

1 Answers

2
votes

The syntax for character literals dictates that you need something between the single quotes:

2.6 Character and String Literals

char  →   '(graphic|space|escape⟨\&⟩)' [remark: heavily simplified]

Character literals are written between single quotes, as in 'a'

Therefore, '' isn't valid syntax for a character. How should it be? There's no character to begin with. The type Char does not contain the notion of not being a character, just as Int does not contain the notion of not existing.

That's exactly what Maybe is for:

my_nthele :: String -> Integer -> Maybe Char
my_nthele [] n = Nothing
my_nthele (x:xs) n  | n == 0 = Just x
                    | otherwise = my_nthele xs (n-1)

By the way, as an exercise, try to make your function more generic, so that one can also use my_nthele [1..10] 3 == Just 4. It's not hard, but let's you play around with Maybe.