Haskell 函数有 "split" 个案例
Haskell Function with "split" cases
如何在这样的函数中创建一个 "split"ting 案例:
getBase64 :: String -> [Char]
getBase64 code
| ("[&":c:r) = c
| _ = ' '
这是行不通的原因:
main.hs:7:11: Not in scope: ‘c’
main.hs:7:13: Not in scope: ‘r’
main.hs:7:18: Not in scope: ‘c’
错误对我来说很明显,但我是新手,不知道如何做 "wish" ...
感谢帮助!
你正试图匹配一个模式,但由于你使用的是 | cond = expr
符号,你实际上是在使用一个守卫。访问此页面以获取有关守卫的更多详细信息:https://en.wikibooks.org/wiki/Haskell/Control_structures#if_and_guards_revisited。 | ("[&":c:r)
实际上意味着 "a list constructed from the string "[&"
and value c
and value r
",Haskell 编译器抱怨变量 c
和 r
不存在。
以下是如何定义具有多个 case 的函数:
getBase64 ("[&":c:r) = c
getBase64 _ = ' '
然而,这行不通,因为"[&"
是一个字符串,而Haskell认为第一个参数是一个字符串列表。字符串是字符列表,您需要像这样修复您的模式:
getBase64 ('[':'&':c:r) = c
getBase64 _ = ' '
查看这些示例以了解有关针对字符串中字符进行模式匹配的更多详细信息: and
然后还有一个问题:getBase64
returns[Char]
。如果那是你想要的,你的代码应该像这样修复:
getBase64 ('[':'&':c:r) = [c]
getBase64 _ = " " -- or [' ']
如何在这样的函数中创建一个 "split"ting 案例:
getBase64 :: String -> [Char]
getBase64 code
| ("[&":c:r) = c
| _ = ' '
这是行不通的原因:
main.hs:7:11: Not in scope: ‘c’
main.hs:7:13: Not in scope: ‘r’
main.hs:7:18: Not in scope: ‘c’
错误对我来说很明显,但我是新手,不知道如何做 "wish" ...
感谢帮助!
你正试图匹配一个模式,但由于你使用的是 | cond = expr
符号,你实际上是在使用一个守卫。访问此页面以获取有关守卫的更多详细信息:https://en.wikibooks.org/wiki/Haskell/Control_structures#if_and_guards_revisited。 | ("[&":c:r)
实际上意味着 "a list constructed from the string "[&"
and value c
and value r
",Haskell 编译器抱怨变量 c
和 r
不存在。
以下是如何定义具有多个 case 的函数:
getBase64 ("[&":c:r) = c
getBase64 _ = ' '
然而,这行不通,因为"[&"
是一个字符串,而Haskell认为第一个参数是一个字符串列表。字符串是字符列表,您需要像这样修复您的模式:
getBase64 ('[':'&':c:r) = c
getBase64 _ = ' '
查看这些示例以了解有关针对字符串中字符进行模式匹配的更多详细信息: and
然后还有一个问题:getBase64
returns[Char]
。如果那是你想要的,你的代码应该像这样修复:
getBase64 ('[':'&':c:r) = [c]
getBase64 _ = " " -- or [' ']