You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Frege中如何安全将String转换为Maybe Int?及异常处理方法

Frege中String转Int的两种实现方案(处理解析失败场景)

一、使用Frege标准库的readMaybe函数

Frege标准库的Text.Read模块提供了readMaybe函数,正好满足你“解析失败返回空值”的需求——可解析的字符串会被转换为Just Int,无法解析时返回Nothing。

示例代码:

import Text.Read (readMaybe)

-- 测试调用
main = do
    print $ readMaybe "123" :: Maybe Int  -- 输出: Just 123
    print $ readMaybe "abc" :: Maybe Int  -- 输出: Nothing

二、调用Java的Integer.parseInt并捕获异常

如果需要直接调用Java的parseInt方法,可通过Frege的异常捕获机制处理解析失败场景,将异常转换为Maybe或Either类型返回。

1. 返回Maybe Int(仅区分成功/失败)

import java.lang.Integer (parseInt)
import Control.Exception (catch)

parseIntSafe :: String -> Maybe Int
parseIntSafe input = catch
    (Just $ parseInt input)
    (\(_:Exception) -> Nothing)

-- 测试调用
main = do
    print $ parseIntSafe "456"  -- 输出: Just 456
    print $ parseIntSafe "xyz"  -- 输出: Nothing

2. 返回Either String Int(携带错误信息)

若需要获取具体异常描述,可返回Either类型:成功时返回Right Int,失败时返回Left携带错误信息:

import java.lang.Integer (parseInt)
import Control.Exception (catch)

parseIntWithError :: String -> Either String Int
parseIntWithError input = catch
    (Right $ parseInt input)
    (\e:Exception -> Left $ e.getMessage())

-- 测试调用
main = do
    print $ parseIntWithError "789"  -- 输出: Right 789
    print $ parseIntWithError "invalid"  -- 输出: Left "For input string: \"invalid\""

内容的提问来源于stack exchange,提问作者halloleo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:12:56