也许是Haskell实现
我在扩展我的知识, ,我想试着用也许是Haskell实现,haskell,Haskell,我在扩展我的知识, ,我想试着用也许做一些性爱或处理。谁能给我一些提示或任何有用的关键字来定义下面的函数(如果我的想法是正确的)?当我成功输入值时,我想返回只返回sts,当我没有输入值时,我想返回什么都不返回。不知道我的想法是否正确,有人纠正我吗 step :: [Int] -> String -> [Int] step (x:y:ys) "*" = (x*y):ys step (x:y:ys) "+" = (x + y):ys step (x:y:ys) "-" = (y - x)
也许
做一些性爱或处理。谁能给我一些提示或任何有用的关键字来定义下面的函数(如果我的想法是正确的)?当我成功输入值时,我想返回只返回sts
,当我没有输入值时,我想返回什么都不返回。不知道我的想法是否正确,有人纠正我吗
step :: [Int] -> String -> [Int]
step (x:y:ys) "*" = (x*y):ys
step (x:y:ys) "+" = (x + y):ys
step (x:y:ys) "-" = (y - x):ys
step xs numString = read numString : xs
你的打字签名是对的。下面是一个可能的实现:
step2:: [Int] -> String -> Maybe [Int]
我们之所以能够做出这种改变,有几个原因:
readMaybe
返回与函数相同类型的结果(Maybe
)
- 常见类型(
可能
)是一个函子
因此,我们可以将fmap
应用于readMaybe
的输出,以合并最后两种情况。对于Maybe
类型,fmap
的工作原理是将Nothing
保留为Nothing
,或者将Just x
更改为Just(f x)
,这正是我们正在做的。@k最后一个案例应该已经处理了所有可能的案例。你能给出一个你认为缺少的具体例子吗?@THEK:如果你想包含关于某个特定故障的更多信息,你可以使用字符串
而不是Maybe
,例如步骤2(x:y:ys)“+”=Right((x+y):ys);步骤2“+”=左“堆栈下溢计算+运算符”
。为了更好的结构和类型安全性,您可以定义data StepError=underflowerError String[Int]| LiteralError String |……
,然后使用任一StepError
而不是EitherString
,例如,step2 xs op@“+”=Left(underflowerError op xs);step2 xs numString=case readMaybe numString of{Just num->Right(num:xs);Nothing->Left(LiteralError numString)}
@JonPurdy从Maybe
切换到或者都是值得单独回答的,无论如何它都会更具可读性:)。回退案例是多余的。@dfeuer公平地说,在我写的答案版本中,这并不是多余的。不管怎样,现在已经修好了。(我还补充了一些解释。)你不能仅仅因为得到了答案就从你的问题中删除代码。
import Text.Read (readMaybe)
step2 :: [Int] -> String -> Maybe [Int]
step2 (x:y:ys) "*" = Just $ (x*y):ys
step2 (x:y:ys) "+" = Just $ (x + y):ys
step2 (x:y:ys) "-" = Just $ (y - x):ys
step2 xs numString | Just num <- readMaybe numString = Just $ num:xs
step2 _ _ = Nothing
import Text.Read (readMaybe)
step2 :: [Int] -> String -> Maybe [Int]
step2 (x:y:ys) "*" = Just $ (x*y):ys
step2 (x:y:ys) "+" = Just $ (x + y):ys
step2 (x:y:ys) "-" = Just $ (y - x):ys
step2 xs numString = fmap (:xs) (readMaybe numString)