【发布时间】:2026-01-24 14:00:01
【问题描述】:
第一个问题:
定义一个使用分隔符值将列表连接在一起的函数。
类型定义应该是这样的:
intersperse :: a -> [[a]] -> [a]
分隔符应出现在列表元素之间,但不应跟在最后一个元素之后。
您的函数应如下所示:
ghci> :load Intersperse
[1 of 1] Compiling Main ( Intersperse.hs, interpreted )
Ok, modules loaded: Main.
ghci> intersperse ',' []
""
ghci> intersperse ',' ["foo"]
"foo"
ghci> intersperse ',' ["foo","bar","baz","quux"]
"foo,bar,baz,quux"
一段时间后我设法解决了它:
intersperse myChar lists
| lists == [] = ""
| otherwise = attach myChar lists
where attach myChar (x:[]) = x
attach myChar (x:xs) = x ++ (myChar : []) ++ attach myChar xs
但是,如您所见,它没有类型定义。
如果我将类型定义放在函数上方,则会出现错误。
为什么?
第二个问题:
在我得到这个解决方案之前,我想在警卫列表中添加另一个警卫。
这个quard应该在第一个后卫之后。
我想检查列表变量中是否只有一个列表,所以我只返回列表变量。
但我不能做那样的守卫(再次,一个错误出现了:-)):
| lists == (x:[]) = lists
这也没用:
| lists == (_:[]) = lists
为什么为什么为什么? :-)。
在此之后,我试图让其他后卫:
| length lists == 1 = lists
但它也引发了错误。
(顺便说一句,我不需要那些守卫,因为我发现“where”关键字之后的第一个模式正是我想要的。
这就是我的意思:
附上 myChar (x:[]) = x
但是,我仍然想了解为什么我尝试的 quards 不起作用。 另外,我很幸运地找到了这个解决方案,而且我不认为每次我都会注意到这样的事情:-)
非常感谢:-)。
附言 这个练习来自本书real world haskell。
【问题讨论】:
-
顺便说一句,这可以很简单地写成
intersperse sep = foldr1 (\i a -> i ++ sep : a)。
标签: haskell