这将很难解释,因为需要了解整个代码的大量背景细节,才能真正从功能上了解我在说什么。但是,我将尽我所能来传达我的主要观点,并希望这已经足够。让我知道是否可以,我将添加更多信息。所以:
我有一个Haskell函数eval :: WExp -> Memory -> WValue
,在不同情况下有很多不同的实例。目前,关于WExp
,Memory
和WValue
的知识并不重要。我的问题是,对于eval
的特定实例,我正在使用lookup
函数,该函数采用eval
(在这种情况下为字符串)的参数搜索该字符串的键值对列表。注意,此lookup
函数不是Prelude中包含的函数。它在.hs文件中是自定义的。如果找到该字符串,则返回与其关联的值,但如果找不到,则返回Nothing
。由于Nothing
的情况,lookup
的类型实际上是Maybe a
,其中a
在这种情况下将是WValue
。由于eval
将返回Maybe WValue
,因此编译器显然会提示该类型不是WValue
。
同样,如果您需要更多有关这些其他类型的信息,我可以提供。只是我认为可能会有某种通用方法从任何返回a
的函数中提取Maybe a
值。如果没有,我想我会在其他地方寻找解决方案:)
最佳答案
做这个
do
input <- getUserInput
result <- lookup input structure
case result of
Just a -> putStrLn $ "I'm so happy you chose "++show a++"."
Nothing -> putStrLn $ "So sorry; "++input++" is not a valid option."
不要这样
do
input <- getUserInput
result <- lookup input structure
case result of
Just a -> putStrLn $ "I'm so happy you chose "++show a++"."
Nothing -> error $ input ++ " is not a valid option."
这很糟糕,因为如果用户输入错误,您的程序只会出现问题。
真的不要这样
有一个名为
fromJust
的函数,该函数尝试从Maybe
中提取一个值,如果找到Nothing
,则抛出错误。看起来像fromJust :: Maybe a -> a
fromJust (Just a) = a
fromJust Nothing = error "Oops, you goofed up, fool."
这使得很难看到出了什么问题。
真的,真的不这样做
但是,如果您想玩火,可以尝试一下,只是为了好玩。这将尝试从
Maybe
中获取一个值,如果找到Nothing
,则将导致真正的崩溃。 “真正崩溃”是指,如果幸运的话,您将遇到段错误;如果不幸运,则将在网络上发布私钥。{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
module Unsafe.FromJust (unsafeFromJust) where
-- Clear sign of bad news
import Unsafe.Coerce (unsafeCoerce)
-- This creates a "closed kind" with types
-- 'JustType and 'NothingType. You could just
-- define datatypes called JustType and NothingType,
-- but this makes the intent clearer.
data MaybeType = JustType | NothingType
data M (t::MaybeType) a where
-- The order of these constructors must not
-- be changed, because this type must look,
-- at runtime, exactly like a Maybe
N :: M 'NothingType a
J :: a -> M 'JustType a
-- A safe sort of fromJust for M.
fromJ :: M 'JustType a -> a
fromJ (J a) = a
-- Really, seriously unsafe.
unsafeFromJust :: Maybe a -> a
unsafeFromJust m = fromJ (unsafeCoerce m)
关于haskell - 在Haskell中从 'a'返回类型获取 'Maybe a'值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28706843/