Haskell:语法错误

Haskell : Syntax error

我正在使用 Haskell 堆栈。

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 解释器显示“src/Len.hs:5:1: 错误: 解析错误(可能是缩进不正确或括号不匹配)"

我不知道哪里出了问题。

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'

因此,'' 不是字符的有效语法。应该怎样?没有字符开始。类型 Char 不包含不是字符的概念,就像 Int 不包含不存在的概念一样。

这正是 Maybe 的用途:

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)

顺便说一句,作为练习,尽量让你的函数更通用,这样也可以使用my_nthele [1..10] 3 == Just 4。这并不难,但让我们来玩玩 Maybe.