Cannot create apply function with static language?

前端 未结 12 886
梦谈多话
梦谈多话 2021-02-04 02:09

I have read that with a statically typed language like Scala or Haskell there is no way to create or provide a Lisp apply function:

(apply #\'+ (lis         


        
12条回答
  •  日久生厌
    2021-02-04 02:38

    A list in Haskell can only store values of one type, so you couldn't do funny stuff like (apply substring ["Foo",2,3]). Neither does Haskell have variadic functions, so (+) can only ever take two arguments.

    There is a $ function in Haskell:

    ($)                     :: (a -> b) -> a -> b
    f $ x                   =  f x
    

    But that's only really useful because it has very low precedence, or as passing around HOFs.

    I imagine you might be able to do something like this using tuple types and fundeps though?

    class Apply f tt vt | f -> tt, f -> vt where
      apply :: f -> tt -> vt
    
    instance Apply (a -> r) a r where
      apply f t = f t
    
    instance Apply (a1 -> a2 -> r) (a1,a2) r where
      apply f (t1,t2) = f t1 t2
    
    instance Apply (a1 -> a2 -> a3 -> r) (a1,a2,a3) r where
      apply f (t1,t2,t3) = f t1 t2 t3
    

    I guess that's a sort of 'uncurryN', isn't it?

    Edit: this doesn't actually compile; superseded by @FUZxxl's answer.

提交回复
热议问题