Grouping functions in Haskell [duplicate] - oop

This question already has answers here:
Partially apply several functions in Haskell
(4 answers)
Closed 4 years ago.
Using Haskell I would like to group functions together as I would using object orientation in other languages. Concretely following the reply to this question
Does Haskell support object oriented programming
let's assume I have a type
data Class = Obj { a :: Int -> Int, b :: Int -> Int }
and now I want to define several other functions (methods as it were) that are derived from a and b. One way to do this is to define something like
c :: Class -> Int -> Int
c obj x = myb (mya x)
where mya = a obj
myb = b obj
d :: Class -> Int -> Int
d obj x = myb (myc x)
where myb = b obj
myc = c obj
However this means that in each regular expression pattern I need to list explicitly (in the ``where'' clause) which other functions I am using. My question is: is there a shorter way to achieve this?

If your goal is just to avoid typing too much, you can use the RecordWildCards extension:
{-# LANGUAGE RecordWildCards #-}
data Class = Obj { a :: Int -> Int, b :: Int -> Int }
f :: Class -> Int -> Int
f Obj{..} x = a x + b x
Then you can use it like this: f (Obj id id) 10 == 20
Note that this shadows the actual "field accessors", so this doesn't work if you still want to use those in the same function for some reason.
Without extensions, you can also always just write
f (Obj a b) x = a x + b x
(Record types can still be pattern matched using the regular constructor syntax).

Related

Access columns of a list by entering them as arguments of a function in elm

type alias Footballer =
{ name : String, age : Float, overall : Float, potential : Float }
type alias Point =
{ pointName : String, x : Float, y : Float }
pointName : Footballer -> Point
pointName x a b c=
Point x.a x.b x.c
I am trying to create points for a scatterplot and want to be able to provide the function with a Player and 3 columns I want to be able to provide variably.
I am struggling with elm, as I am trying to access fields of my List of Football players variably but I can not seem to find a way to do this without rewriting the function pointName for each Variation of Points I want to create.
Elm automatically generates polymorphic accessor functions for all the fields of the records used. (e.g. .age : { a | age : b } -> b) You can use these functions as arguments to pointName and apply them in the body of the function to extract the targeted field.
pointName :
r
-> (r -> String)
-> (r -> Float)
-> (r -> Float)
-> Point
pointName r a b c =
Point (a r) (b r) (c r)
player =
{ name = "Messi", age = 34, overall = 99, potential = 100 }
foo =
pointName player .name .age .potential
bar =
pointName player (.age >> String.fromFloat) .overall .potential

type module with function already implemented ocaml

I have a module type Order which will be implemented in several modules.
The function compare will be implemented in the modules.
module type Order =
sig
type t
val compare: t -> t -> int
end
I want also create a function max :
max a b = if (compare a b > 0) then a else b
I would like to write the definition (Not just declaring ) of this function in my module Order in order to avoid to rewrite the same definition in the submodule which are numerous.
I have tried :
val max a b = if (compare a b > 0) then a else b
and
let max a b = if (compare a b > 0) then a else b
but it doesn't work
You can't implement functions in the signature of a module.
I think that the problem you are having is solved using functors in OCaml.
A code example you can look at to understand how it works is the implementation of Set.
In your case it would look something like:
EDIT: taking into consideration Richard Degenne, octachron and PatJ contributions:
module type Order =
sig
type t
val compare: t -> t -> int
end
module type Util =
sig
type t
val compare: t -> t -> int
val max: t -> t -> t
end
module Make(Ord: Order): Util with type t := Ord.t =
struct
type t = Ord.t
let compare = Ord.compare
let max a b = if (Ord.compare a b > 0) then a else b
end
In order to use it you can do:
(*You first define a module for the specific case of int*)
module IntOrder = struct
type t = int
let compare = compare
end
(*You use the new module to build the corresponding Util module*)
module IntUtil = Make(IntOrder)
(*You can now use the functions defined in Util as if it was any other module*)
let x = IntUtil.max 1 2
let y = IntUtil.compare 1 2
(*But if you try to call it with the wrong type you get an error*)
let z = IntUtil.compare 1.6 2.5

Abstract types in modules in OCaml

I have very simple signature and module in OCaml:
module type S = sig
type t
val y : t
end;;
and
module M2 : S = struct
type t = int
let x = 1
let y = x+2
end;;
I cannot use construction like
M2.y
to get 3 unless i specify the module as
module M2 : S with type t = int = struct ...
Why is it so? There already is statement, that type t = int
The concrete, int value for M2.y is indeed not available because the following two conditions are met:
the type of y is abstract in the signature S
(there is no type t = ... there)
the module M2 is made opaque with respect to the signature S
(in other words, it is restricted to the signature S via the notation : S)
As a result, you indeed obtain:
let test = M2.y ;;
(* val test : M2.t = <abstr> *)
As suggested by the keyword <abstr>, this is related to the notion of abstract type. This notion is a very strong feature enforced by OCaml's typing rules, which prevents any user of a module having signature S to inspect the concrete content of one such abstract type. As a result, this property is very useful to implement so-called abstract data types (ADT) in OCaml, by carefully separating the implementation and the signature of the ADT.
If any of the two conditions above is missing, the type won't be abstract anymore and the concrete value of y will show up.
More precisely:
If the type t is made concrete, you obtain:
module type S = sig
type t = int
val y : t
end
module M2 : S = struct
type t = int
let x = 1
let y = x+2
end
let test = M2.y ;;
(* val test : M2.t = 3 *)
But in practice this is not very interesting because you lose generality. However, a somewhat more interesting approach consists in adding an "evaluator" or a "pretty-printer" function to the signature, such as the value int_of_t below:
module type S = sig
type t
val y : t
val int_of_t : t -> int
end
module M2 : S = struct
type t = int
let x = 1
let y = x+2
let int_of_t x = x
end
let test = M2.(int_of_t y) ;;
(* val test : int = 3 *)
Otherwise, if the module M2 is made transparent, you obtain:
module type S = sig
type t
val y : t
end
module M2 (* :S *) = struct
type t = int
let x = 1
let y = x+2
end
let test = M2.y ;;
(* val test : int = 3 *)
Finally, it may be helpful to note that beyond that feature of abstract types, OCaml also provides a feature of private types that can be viewed as a trade-off between concrete and abstract types used in a modular development. For more details on this notion, see for example Chap. 8 of Caml ref man.

On Church numeral program under Frege

This program compiles and runs correctly under GHC:
type Church a = (a -> a) -> a -> a
ch :: Int -> Church a
ch 0 _ = id
ch n f = f . ch (n-1) f
unch :: Church Int -> Int
unch n = n (+1) 0
suc :: Church a -> Church a
suc n f = f . n f
pre :: Church ((a -> a) -> a) -> Church a
pre n f a = n s z id
where s g h = h (g f)
z = const a
main :: IO ()
main = do let seven = ch 7
eight = suc seven
six = pre seven
print (unch eight)
print (unch six)
But when compiling with Frege I got the following error:
E /home/xgp/work/flab/src/main/frege/flab/fold.fr:23: type error in expression seven
type is : Int
expected: (t1→t1)→t1
E /home/xgp/work/flab/src/main/frege/flab/fold.fr:23: type error in expression seven
type is : (t1→t1)→t1
expected: Int
E /home/xgp/work/flab/src/main/frege/flab/fold.fr:23: type error in expression seven
type is : (t1→t1)→t1
expected: Int
E /home/xgp/work/flab/src/main/frege/flab/fold.fr:23: type error in
expression seven
type is apparently Int
used as function
Why? Is it possible to modify the program to pass the compilation under Frege?
This is one of those rare cases where generalization of types of let bound variables actually does make a difference.
The point is, Frege acts like GHC with pragma -XMonoLocalBinds in that respect, for details see here: https://github.com/Frege/frege/wiki/GHC-Language-Options-vs.-Frege#Let-Generalization and here: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/other-type-extensions.html#typing-binds (there is also a link to a paper of SPJ, that explains the rationale)
What this means, in short, is that all unannotated let bound veriabes will have a monomorphic type, and cannot be used at different types. To restore polymorphism, an explicit type signature is needed.
To make your program compile, it is enough to annotate the binding of seven with
seven :: Church a
Regarding print/println: the former one does not flush the output. So you have in the REPL:
frege> print 'a'
IO ()
frege> print 'b'
IO ()
frege> println "dammit!"
abdammit!
IO ()

How would I translate a Haskell type class into F#?

I'm trying to translate the Haskell core library's Arrows into F# (I think it's a good exercise to understanding Arrows and F# better, and I might be able to use them in a project I'm working on.) However, a direct translation isn't possible due to the difference in paradigms. Haskell uses type-classes to express this stuff, but I'm not sure what F# constructs best map the functionality of type-classes with the idioms of F#. I have a few thoughts, but figured it best to bring it up here and see what was considered to be the closest in functionality.
For the tl;dr crowd: How do I translate type-classes (a Haskell idiom) into F# idiomatic code?
For those accepting of my long explanation:
This code from the Haskell standard lib is an example of what I'm trying to translate:
class Category cat where
id :: cat a a
comp :: cat a b -> cat b c -> cat a c
class Category a => Arrow a where
arr :: (b -> c) -> a b c
first :: a b c -> a (b,d) (c,d)
instance Category (->) where
id f = f
instance Arrow (->) where
arr f = f
first f = f *** id
Attempt 1: Modules, Simple Types, Let Bindings
My first shot at this was to simply map things over directly using Modules for organization, like:
type Arrow<'a,'b> = Arrow of ('a -> 'b)
let arr f = Arrow f
let first f = //some code that does the first op
That works, but it loses out on polymorphism, since I don't implement Categories and can't easily implement more specialized Arrows.
Attempt 1a: Refining using Signatures and types
One way to correct some issues with Attempt 1 is to use a .fsi file to define the methods (so the types enforce easier) and to use some simple type tweaks to specialize.
type ListArrow<'a,'b> = Arrow<['a],['b]>
//or
type ListArrow<'a,'b> = LA of Arrow<['a],['b]>
But the fsi file can't be reused (to enforce the types of the let bound functions) for other implementations, and the type renaming/encapsulating stuff is tricky.
Attempt 2: Object models and interfaces
Rationalizing that F# is built to be OO also, maybe a type hierarchy is the right way to do this.
type IArrow<'a,'b> =
abstract member comp : IArrow<'b,'c> -> IArrow<'a,'c>
type Arrow<'a,'b>(func:'a->'b) =
interface IArrow<'a,'b> with
member this.comp = //fun code involving "Arrow (fun x-> workOn x) :> IArrow"
Aside from how much of a pain it can be to get what should be static methods (like comp and other operators) to act like instance methods, there's also the need to explicitly upcast the results. I'm also not sure that this methodology is still capturing the full expressiveness of type-class polymorphism. It also makes it hard to use things that MUST be static methods.
Attempt 2a: Refining using type extensions
So one more potential refinement is to declare the interfaces as bare as possible, then use extension methods to add functionality to all implementing types.
type IArrow<'a,'b> with
static member (&&&) f = //code to do the fanout operation
Ah, but this locks me into using one method for all types of IArrow. If I wanted a slightly different (&&&) for ListArrows, what can I do? I haven't tried this method yet, but I would guess I can shadow the (&&&), or at least provide a more specialized version, but I feel like I can't enforce the use of the correct variant.
Help me
So what am I supposed to do here? I feel like OO should be powerful enough to replace type-classes, but I can't seem to figure out how to make that happen in F#. Were any of my attempts close? Are any of them "as good as it gets" and that'll have to be good enough?
My brief answer is:
OO is not powerful enough to replace type classes.
The most straightforward translation is to pass a dictionary of operations, as in one typical typeclass implementation. That is if typeclass Foo defines three methods, then define a class/record type named Foo, and then change functions of
Foo a => yadda -> yadda -> yadda
to functions like
Foo -> yadda -> yadda -> yadda
and at each call site you know the concrete 'instance' to pass based on the type at the call-site.
Here's a short example of what I mean:
// typeclass
type Showable<'a> = { show : 'a -> unit; showPretty : 'a -> unit } //'
// instances
let IntShowable =
{ show = printfn "%d"; showPretty = (fun i -> printfn "pretty %d" i) }
let StringShowable =
{ show = printfn "%s"; showPretty = (fun s -> printfn "<<%s>>" s) }
// function using typeclass constraint
// Showable a => [a] -> ()
let ShowAllPretty (s:Showable<'a>) l = //'
l |> List.iter s.showPretty
// callsites
ShowAllPretty IntShowable [1;2;3]
ShowAllPretty StringShowable ["foo";"bar"]
See also
https://web.archive.org/web/20081017141728/http://blog.matthewdoig.com/?p=112
Here's the approach I use to simulate Typeclasses (from http://code.google.com/p/fsharp-typeclasses/ ).
In your case, for Arrows could be something like this:
let inline i2 (a:^a,b:^b ) =
((^a or ^b ) : (static member instance: ^a* ^b -> _) (a,b ))
let inline i3 (a:^a,b:^b,c:^c) =
((^a or ^b or ^c) : (static member instance: ^a* ^b* ^c -> _) (a,b,c))
type T = T with
static member inline instance (a:'a ) =
fun x -> i2(a , Unchecked.defaultof<'r>) x :'r
static member inline instance (a:'a, b:'b) =
fun x -> i3(a, b, Unchecked.defaultof<'r>) x :'r
type Return = Return with
static member instance (_Monad:Return, _:option<'a>) = fun x -> Some x
static member instance (_Monad:Return, _:list<'a> ) = fun x -> [x]
static member instance (_Monad:Return, _: 'r -> 'a ) = fun x _ -> x
let inline return' x = T.instance Return x
type Bind = Bind with
static member instance (_Monad:Bind, x:option<_>, _:option<'b>) = fun f ->
Option.bind f x
static member instance (_Monad:Bind, x:list<_> , _:list<'b> ) = fun f ->
List.collect f x
static member instance (_Monad:Bind, f:'r->'a, _:'r->'b) = fun k r -> k (f r) r
let inline (>>=) x (f:_->'R) : 'R = T.instance (Bind, x) f
let inline (>=>) f g x = f x >>= g
type Kleisli<'a, 'm> = Kleisli of ('a -> 'm)
let runKleisli (Kleisli f) = f
type Id = Id with
static member instance (_Category:Id, _: 'r -> 'r ) = fun () -> id
static member inline instance (_Category:Id, _:Kleisli<'a,'b>) = fun () ->
Kleisli return'
let inline id'() = T.instance Id ()
type Comp = Comp with
static member instance (_Category:Comp, f, _) = (<<) f
static member inline instance (_Category:Comp, Kleisli f, _) =
fun (Kleisli g) -> Kleisli (g >=> f)
let inline (<<<) f g = T.instance (Comp, f) g
let inline (>>>) g f = T.instance (Comp, f) g
type Arr = Arr with
static member instance (_Arrow:Arr, _: _ -> _) = fun (f:_->_) -> f
static member inline instance (_Arrow:Arr, _:Kleisli<_,_>) =
fun f -> Kleisli (return' <<< f)
let inline arr f = T.instance Arr f
type First = First with
static member instance (_Arrow:First, f, _: 'a -> 'b) =
fun () (x,y) -> (f x, y)
static member inline instance (_Arrow:First, Kleisli f, _:Kleisli<_,_>) =
fun () -> Kleisli (fun (b,d) -> f b >>= fun c -> return' (c,d))
let inline first f = T.instance (First, f) ()
let inline second f = let swap (x,y) = (y,x) in arr swap >>> first f >>> arr swap
let inline ( *** ) f g = first f >>> second g
let inline ( &&& ) f g = arr (fun b -> (b,b)) >>> f *** g
Usage:
> let f = Kleisli (fun y -> [y;y*2;y*3]) <<< Kleisli ( fun x -> [ x + 3 ; x * 2 ] ) ;;
val f : Kleisli<int,int list> = Kleisli <fun:f#4-14>
> runKleisli f <| 5 ;;
val it : int list = [8; 16; 24; 10; 20; 30]
> (arr (fun y -> [y;y*2;y*3])) 3 ;;
val it : int list = [3; 6; 9]
> let (x:option<_>) = runKleisli (arr (fun y -> [y;y*2;y*3])) 2 ;;
val x : int list option = Some [2; 4; 6]
> ( (*) 100) *** ((+) 9) <| (5,10) ;;
val it : int * int = (500, 19)
> ( (*) 100) &&& ((+) 9) <| 5 ;;
val it : int * int = (500, 14)
> let x:List<_> = (runKleisli (id'())) 5 ;;
val x : List<int> = [5]
Note: use id'() instead of id
Update: you need F# 3.0 to compile this code, otherwise here's the F# 2.0 version.
And here's a detailed explanation of this technique which is type-safe, extensible and as you can see works even with some Higher Kind Typeclasses.