f [a] Zero or more: many -6ren">
gpt4 book ai didi

haskell - Alternative 的 "some"和 "many"有什么用?

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

Alternative Applicative 的扩展,声明empty , <|>这两个函数:

One or more:

some :: f a -> f [a]

Zero or more:

many :: f a -> f [a]

If defined, some and many should be the least solutions of the equations:

some v = (:) <$> v <*> many v

many v = some v <|> pure []

我找不到 some 的实例和many被定义。 它们的含义和实际用途是什么?它们是否被使用过?仅从这个定义我无法理解他们的目的。

更新:我不是问什么是 Alternative ,就是somemany

最佳答案

TL;DR: some 是一个或多个,many 是通过反复执行相同计算收集的 0 个或多个结果熟悉的maximal munch规则。为了使这一点有意义,必须进行某种状态传递(和更改),以某种方式减少可能性的范围,否则它将无限重复。状态传递和解析密切相关。

<小时/>

一个基本示例实例:with

import Control.Monad(Functor(..))
import Control.Applicative
import Data.Char

-- char string parser
newtype P a = P { runP :: String -> [(a,String)] }

-- runP (P p) s = p s

instance Functor P where
-- fmap :: (a -> b) -> f a -> f b
fmap f (P q) = P (\s -> [ (f y,ys) | (y,ys) <- q s])

instance Applicative P where
-- pure :: a -> f a
pure x = P (\s -> [(x,s)])
-- (<*>) :: f (a -> b) -> f a -> f b
P p <*> P q = P (\s -> [(x y, ys) | (x,xs) <- p s, (y,ys) <- q xs])

letter = P p where -- sample parser
p (x:xs) | isAlpha x = [(x,xs)]
p _ = []

我们有

*Main Data.Char> runP letter "123"
[]
*Main Data.Char> runP letter "a123"
[('a',"123")]
*Main Data.Char> runP ( (:) <$> letter <*> pure []) "a123"
[("a","123")]
*Main Data.Char> runP ( (:) <$> letter <*> ((:)<$>letter <*> pure []) ) "a123"
[]
*Main Data.Char> runP ( (:) <$> letter <*> ((:)<$>letter <*> pure []) ) "ab123"
[("ab","123")] -- NOT NICE ^^^^^^^^^^^^^^^^^^^^ -}

然后,与

instance Alternative P where
-- (<|>) :: f a -> f a -> f a
P p <|> P q = P (\s-> p s ++ q s)
-- empty :: f a -- the identity of <|>
empty = P (\s-> [])

我们得到

*Main Data.Char> runP (many letter) "ab123"
[("ab","123"),("a","b123"),("","ab123")]
*Main Data.Char> runP (some letter) "ab123"
[("ab","123"),("a","b123")]

*Main Data.Char> runP (optional letter) "ab123"
[(Just 'a',"b123"),(Nothing,"ab123")]
*Main Data.Char> runP (optional letter) "123"
[(Nothing,"123")]

Prelude Main Data.Traversable> runP (sequenceA $ replicate 2 letter) "ab123"
[("ab","123")] -- NICE ^^^^^^^^^^^^^^^^^^^
-}

关于haskell - Alternative 的 "some"和 "many"有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108608/

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