Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
也许是Haskell实现_Haskell - Fatal编程技术网

也许是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)