将字符串列表应用于任意函数 [英] applying a list of Strings to an arbitrary function

查看:84
本文介绍了将字符串列表应用于任意函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a function which allows you to "apply" a list of Strings to an arbitrary function. Here's what I've got so far:

{-# 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"

我想写类似下面的东西:

I'd like to write something like the following:

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

但是GHC抱怨:Could not deduce (Show a0) arising from a use of 'show' ...

但是,特定的定义有效:

However, specific definitions work:

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?

Is there a way I can get wrap to work? Is there a better way to implement apply?

推荐答案

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

You can also try changing the declaration of Apply to

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

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

And adding the FunctionalDependencies extension, your current wrap signature works

我相信这都与无法推断"错误之后出现的重叠实例"错误有关.

I believe this is all related to the Overlapping Instances error that you get after the "Could not deduce" error.

这篇关于将字符串列表应用于任意函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆