Haskell 可能输入 -> 类型

标签 haskell option-type

我遇到了这个问题:

Couldn't match expected type ‘Int’ with actual type ‘Maybe Int’

我能以某种方式将“Maybe Int”转换为“Int”吗??

if index == Nothing 
   then 
     do 
       let index = 0
       putStrLn(fancyPrint2 $ kaasasOlevList !! index)
   else 
     do 
       let index = index
       putStrLn(fancyPrint2 $ kaasasOlevList !! index)

我这样试过,但这给了我:

Exception: <<loop>>

最佳答案

你有几种不同的选择来解决这个问题

首先是使用您的 if 语句,但稍作修改(尽管避免这样做)

if index == Nothing 
   then 
     do 
       let index' = 0
       putStrLn $ fancyPrint2 $ kaasasOlevList !! index'
   else 
     do 
       let (Just index') = index
       putStrLn $ fancyPrint2 $ kaasasOlevList !! index'

我在这里写 index',因为 Haskell 不允许您覆盖现有变量,但是它允许您隐藏它们。但一般来说,更好的做法是在变量的“修改”版本末尾加上“素数”符号 (')。这样您就可以在需要时随时访问原件。

其次,您可以使用 case 表达式将您的代码转换为

case index of
  Just i  -> putStrLn $ fancyPrint2 $ kaasasOlevList !! i
  Nothing -> putStrLn $ fancyPrint2 $ kaasasOlevList !! 0

或者,如果您使用 where 子句稍微清理一下:

case index of
  Just i  -> putIndex i
  Nothing -> putIndex 0
where putIndex x = putStrLn $ fancyPrint2 $ kaasasOlevList !! x

最后还有 fromMaybe 可以让你这样做:

import Data.Maybe (fromMaybe)

-- ...

do
  let index' = fromMaybe 0 index
  putStrLn $ fancyPrint2 $ kaasasOlevList !! index'

你也可以使用守卫。但是看到我不知道你的代码片段来自哪里,我不知道使用守卫是否合理。

您可以阅读更多关于守卫、case 表达式和模式匹配的信息 here

关于Haskell 可能输入 -> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622265/

相关文章:

haskell - 某些用户的 cabal 安装时未出现进度消息

haskell - 是否可以在 Haskell 中部分应用第 n 个参数?

sorting - haskell 排序

java - 如何使用 Java 8 Optionals,如果所有三个都存在则执行一个 Action ?

C# FP : Validation and execution with error handling functional way - space for improvement?

java - 使用 isPresent() 从 Optional 内部获取值

haskell -斯科蒂 : Set custom headers (x-frame-options)

list - Haskell:在列表和元组之间

swift - 意外地发现 nil 意外 - struct init?不工作

swift - 在 Swift2 中如何解决这个错误?