字符串函数中的Haskell字符

嘿,我是 Haskell 的新手,我遇到了一个小问题。

我想编写一个函数来检查给定的字符是否在给定的字符串中。这是我的代码:

inString :: String -> Char -> Bool 
inString [] _ = False 
inString x c = x == c
inString x:xs c = inString xs c

对我来说这很有意义,因为我知道字符串只是字符列表。但我得到了一个Parse error in pattern : inString.

任何帮助,将不胜感激。

回答

您必须考虑每个表达式的类型:

inString :: String -> Char -> Bool 
inString [] _ = False 
inString (x::String) (c::Char) = x == c -- won't compile char and strings cannot be compared because they have different type
inString (x:xs) c = inString xs c -- add parenthesis to x:xs -> (x:xs)

所以一种可能的方法是:

inString :: String -> Char -> Bool 
inString [] _ = False 
inString (x:xs) c = if x == c then True else inString xs c


以上是字符串函数中的Haskell字符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>