【发布时间】:2021-08-19 21:14:17
【问题描述】:
为了学习 Haskell,我尝试改编康拉德·巴尔斯基 (Conrad Barski) 的优秀著作《Land of Lisp》中的一些练习。我们的想法是制作一个简单的文本游戏引擎。
具体我试过了:
type Clau = String
type Descripcio = String
type Valors = [String]
-- NOTE : Ideas of types http://learnyouahaskell.com/making-our-own-types-and-typeclasses
data Lloc = Lloc String String String deriving (Show)
llocSituacio :: Lloc -> String
llocSituacio (Lloc situacio _ _ ) = situacio
llocDireccio :: Lloc -> String
llocDireccio (Lloc _ direccio _) = direccio
llocPas :: Lloc -> String
llocPas ( Lloc _ _ pas) = pas
nodes :: [(Clau,Descripcio)]
nodes = [("living-room","you are in the living-room. a wizard is snoring loudly on the couch.")
,("garden","you are in a beautiful garden. there is a well in front of you.")
, ("attic", "you are in the attic. there is a giant welding torch in the corner.")]
edges :: [([Char], [Lloc])]
edges = [ ("living-room", [(Lloc "garden" "west" "door"), ( Lloc "attic" "upstairs" "ladder") ])
, ("attic", [(Lloc "living-room" "east" "door")])
, ("garden", [(Lloc "living-room" "east" "door")])]
describePath :: Lloc -> String
describePath e = "There is " ++ llocPas e ++ " going " ++ llocDireccio e ++ " from here."
起初,它似乎运作良好。例如:
*TextGame> describePath (Lloc "living-room" "east" "door")
"There is door going east from here."
但是当我尝试将函数应用到列表时,我得到了这个错误:
situacio = "garden"
map (describePath) (lookup situacio edges)
<interactive>:2:22: error:
• Couldn't match expected **type ‘[Maybe Lloc]’**
with actual **type ‘Maybe [Lloc]’**
• In the second argument of ‘map’, namely ‘(lookup situacio edges)’
In the expression: map (describePath) (lookup situacio edges)
In an equation for ‘it’:
it = map (describePath) (lookup situacio edges)
错误很明显,但我无法解决它。我想解析 Maybe 的值列表并使用运行良好的函数 describePath 打印路径:
有什么想法吗?此外,如果有人想分享替代方案或觉得此代码可能更符合 Haskell 风格,请随时讨论。
【问题讨论】:
-
也许这个旧答案有帮助? stackoverflow.com/questions/3375483/…
-
它是map-function,而不是map。
标签: dictionary haskell functional-programming lisp maybe