gpt4 book ai didi

haskell - 将字符串列表应用于任意函数

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

我正在尝试编写一个函数,它允许您将字符串列表“应用”到任意函数。到目前为止,这是我得到的:

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, OverlappingInstances, TypeFamilies #-}

class Apply a c
where apply :: a -> [String] -> c

instance (Read a, Apply b c) => Apply (a -> b) c
where apply _ [] = error "not enough arguments"
apply f (x:xs) = apply (f (read x)) xs

instance (a ~ b) => Apply a b
where apply f [] = f
apply _ (_:_) = error "too many arguments"

例子:

g1 :: Int -> Bool
g1 x = x > 10

g2 :: Bool -> Int -> Int
g2 b n = if b then 10*n else n-1

test1 = apply g1 ["3"] -- False
test2 = apply g2 ["True", "33"] -- 330
test3 = apply g2 ["False", "0"] -- -1
test4 = apply g2 [] -- error "not enough arguments"
test5 = apply g2 ["True", "3", "x"] -- error "too many arguments"
test6 = apply (length :: [Int] -> Int) ["[4,5,6]"] -- 3
test7 = apply (tail :: [Char] -> [Char]) [ "['a','b','c']" ] -- "bc"

我想写如下内容:

wrap :: (Show b, Apply a b) => a -> ([String] -> String)
wrap f xs = show $ apply f xs

但是 GHC 提示:Could not deduce (Show a0) areas of a use of 'show' ...

但是,特定定义有效:

w1 xs = show $ apply g1 xs
w2 xs = show $ apply g2 xs

并导致 [String] -> String 类型的函数:

test8 = w1 ["20"]          -- "True"
test9 = w2 ["False", "3" ] -- "2"

有没有办法让 wrap 工作?有没有更好的方法来实现apply

最佳答案

您也可以尝试更改 Apply to 的声明

class Apply a c | a -> c
where apply :: a -> [String] -> c

并添加 FunctionalDependencies 扩展,您当前的包装签名有效

我相信这都与您在“无法推断”错误后遇到的重叠实例错误有关。

关于haskell - 将字符串列表应用于任意函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21362498/

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