gpt4 book ai didi

haskell - 如何在没有缩进树的情况下处理嵌套的 case 语句?

转载 作者:行者123 更新时间:2023-12-02 20:36:02 25 4
gpt4 key购买 nike

我偶尔会遇到一个小问题,即我有一组嵌套的 case 语句,处理起来很麻烦。我是否可以使用任何技术/模式来获得一个函数列表(这相当于示例的 case ... 语句),评估所有函数,并选择第一个与模式(例如:右 x)?

我将它们放入列表时遇到的一个具体问题是它们不一定是同一类型(我认为是单态性限制)。例如以下内容:

  let possibleTags = [
parse (parseFileReference) "file reference" xStr
, parse (parseGitDiffReference) "git diff tag" xStr
]

产生以下错误:

• Couldn't match type ‘GitDiffReference’ with ‘FileReference’
Expected type: Either ParseError FileReference
Actual type: Either ParseError GitDiffReference
• In the expression:
parse (parseGitDiffReference) "git diff tag" xStr
In the expression:
[parse (parseFileReference) "file reference" xStr,
parse (parseGitDiffReference) "git diff tag" xStr]
In an equation for ‘possibleTags’:
possibleTags
= [parse (parseFileReference) "file reference" xStr,
parse (parseGitDiffReference) "git diff tag" xStr]
<小时/>
abc :: Int -> String
abc = undefined

abc2 :: Int -> Float
abc2 = undefined

abc3 :: Int -> Int
abc3 = undefined

example :: Int -> Maybe String
example x = case abc x of
("yes") -> Just "abc"
("no") -> case abc2 x of
1.0 -> Just "abc2"
2.0 -> case abc3 x of
100 -> Just "abc3"
200 -> Nothing

我理想地寻找类似下面的东西(无效代码):

-- Psuedo code
example :: Int -> Maybe String
example =
if (abc x && "yes") then Just "abc"
if (abc2 x && 1.0) then Just "abc2"
if (abc3 x && 100) then Just "abc3"

使用 if 条件的问题是我无法(据我所知)进行模式匹配,例如 if (Just x)

最佳答案

翻译确切的示例(保持非详尽的模式匹配不变):

import Data.Foldable


example2 :: Int -> Maybe String
example2 x = asum tests
where
tests =
[ case abc x of
"yes" -> Just "abc"
"no" -> Nothing
, case abc2 x of
1.0 -> Just "abc2"
2.0 -> Nothing
, case abc3 x of
100 -> Just "abc3"
200 -> Nothing
]

关于haskell - 如何在没有缩进树的情况下处理嵌套的 case 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com