加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 将第一个参数转换为第n个函数

发布时间:2020-12-16 09:20:43 所属栏目:安全 来源:网络整理
导读:给定一个至少有n个参数的函数,我想旋转第一个参数,使其成为第n个参数.例如(在无类型的lambda演算中): r(λa. a) = λa. ar(λa. λb. a b) = λb. λa. a br(λa. λb. λc. a b c) = λb. λc. λa. a b cr(λa. λb. λc. λd. a b c d) = λb. λc. λd.



给定一个至少有n个参数的函数,我想旋转第一个参数,使其成为第n个参数.例如(在无类型的lambda演算中):

r(λa. a)                   = λa. a
r(λa. λb. a b)             = λb. λa. a b
r(λa. λb. λc. a b c)       = λb. λc. λa. a b c
r(λa. λb. λc. λd. a b c d) = λb. λc. λd. λa. a b c d

等等.

你能用通用的方式写r吗?如果你知道n> = 2怎么办?

以下是Scala中提到的问题:

trait E
case class Lam(i: E => E) extends E
case class Lit(i: Int) extends E
case class Ap(e: E,e: E) extends E

旋转应该取Lam(a => Lam(b => Lam(c => Ap(Ap(a,b),c)))),并返回Lam(b => Lam(c = Lam(a => Ap(Ap(a,c))))).

解决方法

诀窍是标记所涉及的功能的“最终”值,因为从正常的haskell,a – > b和a – > (b→c)只是单个变量的函数.
但是,如果我们这样做,我们可以做到这一点.

{-# LANGUAGE TypeFamilies,FlexibleInstances,FlexibleContexts #-}
module Rotate where

data Result a = Result a

class Rotate f where
  type After f
  rotate :: f -> After f

instance Rotate (a -> Result b) where
  type After (a -> Result b) = a -> Result b
  rotate = id

instance Rotate (a -> c) => Rotate (a -> b -> c) where
  type After (a -> b -> c) = b -> After (a -> c)
  rotate = (rotate .) . flip

然后,看看它在行动:

f0 :: Result a
f0 = Result undefined

f1 :: Int -> Result a
f1 = const f0

f2 :: Char -> Int -> Result a
f2 = const f1

f3 :: Float -> Char -> Int -> Result a
f3 = const f2

f1' :: Int -> Result a
f1' = rotate f1

f2' :: Int -> Char -> Result a
f2' = rotate f2

f3' :: Char -> Int -> Float -> Result a
f3' = rotate f3

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读