119 people like it.

The Haskell const function

The const function is simple, but you can use it to make your code more legible. In this example we convert a unary function to a function of arity 2 (that ignores the second argument). Also by using the flip function from Haskell (which is equally easy to define) you can ignore the first argument.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
// The const function
let ct a _ = a

// The flip function; even though I'm not gonna use it here
let flip f x y = f y x

// And now a use case 

// I'm writing a toy interpreter so the following code is taken straight 
// from that

type Exp = 
    // ...
    // Lambdas are expressed as F# function that takes a list of Exps and an env
    | Lambda of (Exp list -> Env -> Exp)
    // ...
and Env = (string * Exp) list

// Built-ins receive evaluated arguments so they don't care about the env.
// By composing the function we get with ct we're basically converting a function
// of arity 1 to a function of arity 2 that just ignores its second argument

let builtin f = Lambda (f >> ct)
val ct : a:'a -> 'b -> 'a

Full name: Script.ct
val a : 'a
val flip : f:('a -> 'b -> 'c) -> x:'b -> y:'a -> 'c

Full name: Script.flip
val f : ('a -> 'b -> 'c)
val x : 'b
val y : 'a
type Exp = | Lambda of (Exp list -> Env -> Exp)

Full name: Script.Exp
union case Exp.Lambda: (Exp list -> Env -> Exp) -> Exp
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
type Env = (string * Exp) list

Full name: Script.Env
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val builtin : f:(Exp list -> Exp) -> Exp

Full name: Script.builtin
val f : (Exp list -> Exp)
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/19
Posted:14 years ago
Author:Alex Muscar
Tags: haskell functions