簡體   English   中英

pipe 相互結合的功能類型

[英]A type for functions that pipe into each other

我想處理一個可以存儲 f1、f2、f3、f4、f5 的抽象......

:t f5 . f4 . f3 . f2 . f1
-- String -> Int

我不太關心中間結果,所以我想做類似的事情:

data PipeFunction a z = [(a->b), (b->c), ..., (y->z)] -- pseudocode

什么樣的抽象可以讓我這樣做? 目前我唯一能想到的就是:

newtype PipeFunction a b c = PipeFunction (a->b, c->d)

但我希望它適用於任意數量的功能。

編輯:一個潛在的說明示例/用例,有一個抽象,可以讓我更優雅地執行這個: 反應式應用示例

EDIT2:跟進。 是否可以交換類型對齊序列的元素? 處理這樣的事情:

swapPipe :: PipeFunction a z -> Int -> (b -> c) -> PipeFunction a z
swapPipe Nil _ _ = Nil
swapPipe (f :> fs) i g = f :> swapPipe fs i g
swapPipe (f :> fs) 0 g = g :> fs

像 Idris 這樣的依賴類型會有用嗎?

您可以使用 GADT 存儲它們,如下所示:

{-# LANGUAGE GADTs #-}

data PipeFunction a z where
  Nil :: PipeFunction a a
  (:>) :: Show b => (a -> b) -> PipeFunction b z -> PipeFunction a z

infixr 5 :>

以及您問題中的示例:

import Data.Function
import Data.List

showPipe :: PipeFunction a z -> a -> [String]
showPipe Nil _ = []
showPipe (f :> fs) x = show y : showPipe fs y
  where y = f x

main = print $ showPipe (sort :> group :> sortBy (flip compare `on` length) :> head :> head :> Nil) [3,1,2,2,3,5,5,6,3,5,5,3]

-- Result: ["[1,2,2,3,3,3,3,5,5,5,5,6]","[[1],[2,2],[3,3,3,3],[5,5,5,5],[6]]","[[3,3,3,3],[5,5,5,5],[2,2],[1],[6]]","[3,3,3,3]","3"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM